repo_id stringclasses 875 values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
googleapis/google-cloud-java | 37,942 | java-cloudcontrolspartner/proto-google-cloud-cloudcontrolspartner-v1beta/src/main/java/com/google/cloud/cloudcontrolspartner/v1beta/CreateCustomerRequest.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/cloudcontrolspartner/v1beta/customers.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.cloudcontrolspartner.v1beta;
/**
*
*
* <pre>
* Request to create a customer
* </pre>
*
* Protobuf type {@code google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest}
*/
public final class CreateCustomerRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest)
CreateCustomerRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateCustomerRequest.newBuilder() to construct.
private CreateCustomerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateCustomerRequest() {
parent_ = "";
customerId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateCustomerRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.cloudcontrolspartner.v1beta.CustomersProto
.internal_static_google_cloud_cloudcontrolspartner_v1beta_CreateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.cloudcontrolspartner.v1beta.CustomersProto
.internal_static_google_cloud_cloudcontrolspartner_v1beta_CreateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest.class,
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CUSTOMER_FIELD_NUMBER = 2;
private com.google.cloud.cloudcontrolspartner.v1beta.Customer customer_;
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the customer field is set.
*/
@java.lang.Override
public boolean hasCustomer() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The customer.
*/
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.Customer getCustomer() {
return customer_ == null
? com.google.cloud.cloudcontrolspartner.v1beta.Customer.getDefaultInstance()
: customer_;
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.CustomerOrBuilder getCustomerOrBuilder() {
return customer_ == null
? com.google.cloud.cloudcontrolspartner.v1beta.Customer.getDefaultInstance()
: customer_;
}
public static final int CUSTOMER_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
customerId_ = 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, getCustomer());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, customerId_);
}
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, getCustomer());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, customerId_);
}
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.cloudcontrolspartner.v1beta.CreateCustomerRequest)) {
return super.equals(obj);
}
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest other =
(com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasCustomer() != other.hasCustomer()) return false;
if (hasCustomer()) {
if (!getCustomer().equals(other.getCustomer())) return false;
}
if (!getCustomerId().equals(other.getCustomerId())) 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 (hasCustomer()) {
hash = (37 * hash) + CUSTOMER_FIELD_NUMBER;
hash = (53 * hash) + getCustomer().hashCode();
}
hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest 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.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest 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.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest 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.cloudcontrolspartner.v1beta.CreateCustomerRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
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.cloudcontrolspartner.v1beta.CreateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest 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.cloudcontrolspartner.v1beta.CreateCustomerRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to create a customer
* </pre>
*
* Protobuf type {@code google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest)
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.cloudcontrolspartner.v1beta.CustomersProto
.internal_static_google_cloud_cloudcontrolspartner_v1beta_CreateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.cloudcontrolspartner.v1beta.CustomersProto
.internal_static_google_cloud_cloudcontrolspartner_v1beta_CreateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest.class,
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest.Builder.class);
}
// Construct using
// com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getCustomerFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
customer_ = null;
if (customerBuilder_ != null) {
customerBuilder_.dispose();
customerBuilder_ = null;
}
customerId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.cloudcontrolspartner.v1beta.CustomersProto
.internal_static_google_cloud_cloudcontrolspartner_v1beta_CreateCustomerRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
getDefaultInstanceForType() {
return com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest build() {
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest buildPartial() {
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest result =
new com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.customer_ = customerBuilder_ == null ? customer_ : customerBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.customerId_ = customerId_;
}
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.cloudcontrolspartner.v1beta.CreateCustomerRequest) {
return mergeFrom(
(com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest other) {
if (other
== com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasCustomer()) {
mergeCustomer(other.getCustomer());
}
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
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(getCustomerFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
customerId_ = 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. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent resource
* Format: `organizations/{organization}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.cloudcontrolspartner.v1beta.Customer customer_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.cloudcontrolspartner.v1beta.Customer,
com.google.cloud.cloudcontrolspartner.v1beta.Customer.Builder,
com.google.cloud.cloudcontrolspartner.v1beta.CustomerOrBuilder>
customerBuilder_;
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the customer field is set.
*/
public boolean hasCustomer() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The customer.
*/
public com.google.cloud.cloudcontrolspartner.v1beta.Customer getCustomer() {
if (customerBuilder_ == null) {
return customer_ == null
? com.google.cloud.cloudcontrolspartner.v1beta.Customer.getDefaultInstance()
: customer_;
} else {
return customerBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setCustomer(com.google.cloud.cloudcontrolspartner.v1beta.Customer value) {
if (customerBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
customer_ = value;
} else {
customerBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setCustomer(
com.google.cloud.cloudcontrolspartner.v1beta.Customer.Builder builderForValue) {
if (customerBuilder_ == null) {
customer_ = builderForValue.build();
} else {
customerBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeCustomer(com.google.cloud.cloudcontrolspartner.v1beta.Customer value) {
if (customerBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& customer_ != null
&& customer_
!= com.google.cloud.cloudcontrolspartner.v1beta.Customer.getDefaultInstance()) {
getCustomerBuilder().mergeFrom(value);
} else {
customer_ = value;
}
} else {
customerBuilder_.mergeFrom(value);
}
if (customer_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearCustomer() {
bitField0_ = (bitField0_ & ~0x00000002);
customer_ = null;
if (customerBuilder_ != null) {
customerBuilder_.dispose();
customerBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.cloudcontrolspartner.v1beta.Customer.Builder getCustomerBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getCustomerFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.cloudcontrolspartner.v1beta.CustomerOrBuilder getCustomerOrBuilder() {
if (customerBuilder_ != null) {
return customerBuilder_.getMessageOrBuilder();
} else {
return customer_ == null
? com.google.cloud.cloudcontrolspartner.v1beta.Customer.getDefaultInstance()
: customer_;
}
}
/**
*
*
* <pre>
* Required. The customer to create.
* </pre>
*
* <code>
* .google.cloud.cloudcontrolspartner.v1beta.Customer customer = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.cloudcontrolspartner.v1beta.Customer,
com.google.cloud.cloudcontrolspartner.v1beta.Customer.Builder,
com.google.cloud.cloudcontrolspartner.v1beta.CustomerOrBuilder>
getCustomerFieldBuilder() {
if (customerBuilder_ == null) {
customerBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.cloudcontrolspartner.v1beta.Customer,
com.google.cloud.cloudcontrolspartner.v1beta.Customer.Builder,
com.google.cloud.cloudcontrolspartner.v1beta.CustomerOrBuilder>(
getCustomer(), getParentForChildren(), isClean());
customer_ = null;
}
return customerBuilder_;
}
private java.lang.Object customerId_ = "";
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
customerId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The customer id to use for the customer, which will become the
* final component of the customer's resource name. The specified value must
* be a valid Google cloud organization id.
* </pre>
*
* <code>string customer_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
customerId_ = 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.cloudcontrolspartner.v1beta.CreateCustomerRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest)
private static final com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest();
}
public static com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateCustomerRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateCustomerRequest>() {
@java.lang.Override
public CreateCustomerRequest 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<CreateCustomerRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateCustomerRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.cloudcontrolspartner.v1beta.CreateCustomerRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,995 | java-kms/proto-google-cloud-kms-v1/src/main/java/com/google/cloud/kms/v1/CreateEkmConnectionRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/kms/v1/ekm_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.kms.v1;
/**
*
*
* <pre>
* Request message for
* [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection].
* </pre>
*
* Protobuf type {@code google.cloud.kms.v1.CreateEkmConnectionRequest}
*/
public final class CreateEkmConnectionRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.kms.v1.CreateEkmConnectionRequest)
CreateEkmConnectionRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateEkmConnectionRequest.newBuilder() to construct.
private CreateEkmConnectionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateEkmConnectionRequest() {
parent_ = "";
ekmConnectionId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateEkmConnectionRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.kms.v1.EkmServiceProto
.internal_static_google_cloud_kms_v1_CreateEkmConnectionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.kms.v1.EkmServiceProto
.internal_static_google_cloud_kms_v1_CreateEkmConnectionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.kms.v1.CreateEkmConnectionRequest.class,
com.google.cloud.kms.v1.CreateEkmConnectionRequest.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 location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int EKM_CONNECTION_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object ekmConnectionId_ = "";
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The ekmConnectionId.
*/
@java.lang.Override
public java.lang.String getEkmConnectionId() {
java.lang.Object ref = ekmConnectionId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ekmConnectionId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for ekmConnectionId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEkmConnectionIdBytes() {
java.lang.Object ref = ekmConnectionId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ekmConnectionId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int EKM_CONNECTION_FIELD_NUMBER = 3;
private com.google.cloud.kms.v1.EkmConnection ekmConnection_;
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the ekmConnection field is set.
*/
@java.lang.Override
public boolean hasEkmConnection() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The ekmConnection.
*/
@java.lang.Override
public com.google.cloud.kms.v1.EkmConnection getEkmConnection() {
return ekmConnection_ == null
? com.google.cloud.kms.v1.EkmConnection.getDefaultInstance()
: ekmConnection_;
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.kms.v1.EkmConnectionOrBuilder getEkmConnectionOrBuilder() {
return ekmConnection_ == null
? com.google.cloud.kms.v1.EkmConnection.getDefaultInstance()
: ekmConnection_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ekmConnectionId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, ekmConnectionId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getEkmConnection());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ekmConnectionId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, ekmConnectionId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEkmConnection());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.kms.v1.CreateEkmConnectionRequest)) {
return super.equals(obj);
}
com.google.cloud.kms.v1.CreateEkmConnectionRequest other =
(com.google.cloud.kms.v1.CreateEkmConnectionRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getEkmConnectionId().equals(other.getEkmConnectionId())) return false;
if (hasEkmConnection() != other.hasEkmConnection()) return false;
if (hasEkmConnection()) {
if (!getEkmConnection().equals(other.getEkmConnection())) 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) + EKM_CONNECTION_ID_FIELD_NUMBER;
hash = (53 * hash) + getEkmConnectionId().hashCode();
if (hasEkmConnection()) {
hash = (37 * hash) + EKM_CONNECTION_FIELD_NUMBER;
hash = (53 * hash) + getEkmConnection().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.kms.v1.CreateEkmConnectionRequest 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
* [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection].
* </pre>
*
* Protobuf type {@code google.cloud.kms.v1.CreateEkmConnectionRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.kms.v1.CreateEkmConnectionRequest)
com.google.cloud.kms.v1.CreateEkmConnectionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.kms.v1.EkmServiceProto
.internal_static_google_cloud_kms_v1_CreateEkmConnectionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.kms.v1.EkmServiceProto
.internal_static_google_cloud_kms_v1_CreateEkmConnectionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.kms.v1.CreateEkmConnectionRequest.class,
com.google.cloud.kms.v1.CreateEkmConnectionRequest.Builder.class);
}
// Construct using com.google.cloud.kms.v1.CreateEkmConnectionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEkmConnectionFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
ekmConnectionId_ = "";
ekmConnection_ = null;
if (ekmConnectionBuilder_ != null) {
ekmConnectionBuilder_.dispose();
ekmConnectionBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.kms.v1.EkmServiceProto
.internal_static_google_cloud_kms_v1_CreateEkmConnectionRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.kms.v1.CreateEkmConnectionRequest getDefaultInstanceForType() {
return com.google.cloud.kms.v1.CreateEkmConnectionRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.kms.v1.CreateEkmConnectionRequest build() {
com.google.cloud.kms.v1.CreateEkmConnectionRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.kms.v1.CreateEkmConnectionRequest buildPartial() {
com.google.cloud.kms.v1.CreateEkmConnectionRequest result =
new com.google.cloud.kms.v1.CreateEkmConnectionRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.kms.v1.CreateEkmConnectionRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.ekmConnectionId_ = ekmConnectionId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.ekmConnection_ =
ekmConnectionBuilder_ == null ? ekmConnection_ : ekmConnectionBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.kms.v1.CreateEkmConnectionRequest) {
return mergeFrom((com.google.cloud.kms.v1.CreateEkmConnectionRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.kms.v1.CreateEkmConnectionRequest other) {
if (other == com.google.cloud.kms.v1.CreateEkmConnectionRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getEkmConnectionId().isEmpty()) {
ekmConnectionId_ = other.ekmConnectionId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasEkmConnection()) {
mergeEkmConnection(other.getEkmConnection());
}
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:
{
ekmConnectionId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getEkmConnectionFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the location associated with the
* [EkmConnection][google.cloud.kms.v1.EkmConnection], in the format
* `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object ekmConnectionId_ = "";
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The ekmConnectionId.
*/
public java.lang.String getEkmConnectionId() {
java.lang.Object ref = ekmConnectionId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ekmConnectionId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for ekmConnectionId.
*/
public com.google.protobuf.ByteString getEkmConnectionIdBytes() {
java.lang.Object ref = ekmConnectionId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ekmConnectionId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The ekmConnectionId to set.
* @return This builder for chaining.
*/
public Builder setEkmConnectionId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ekmConnectionId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearEkmConnectionId() {
ekmConnectionId_ = getDefaultInstance().getEkmConnectionId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`.
* </pre>
*
* <code>string ekm_connection_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for ekmConnectionId to set.
* @return This builder for chaining.
*/
public Builder setEkmConnectionIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ekmConnectionId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.kms.v1.EkmConnection ekmConnection_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.kms.v1.EkmConnection,
com.google.cloud.kms.v1.EkmConnection.Builder,
com.google.cloud.kms.v1.EkmConnectionOrBuilder>
ekmConnectionBuilder_;
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the ekmConnection field is set.
*/
public boolean hasEkmConnection() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The ekmConnection.
*/
public com.google.cloud.kms.v1.EkmConnection getEkmConnection() {
if (ekmConnectionBuilder_ == null) {
return ekmConnection_ == null
? com.google.cloud.kms.v1.EkmConnection.getDefaultInstance()
: ekmConnection_;
} else {
return ekmConnectionBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEkmConnection(com.google.cloud.kms.v1.EkmConnection value) {
if (ekmConnectionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ekmConnection_ = value;
} else {
ekmConnectionBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEkmConnection(com.google.cloud.kms.v1.EkmConnection.Builder builderForValue) {
if (ekmConnectionBuilder_ == null) {
ekmConnection_ = builderForValue.build();
} else {
ekmConnectionBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEkmConnection(com.google.cloud.kms.v1.EkmConnection value) {
if (ekmConnectionBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& ekmConnection_ != null
&& ekmConnection_ != com.google.cloud.kms.v1.EkmConnection.getDefaultInstance()) {
getEkmConnectionBuilder().mergeFrom(value);
} else {
ekmConnection_ = value;
}
} else {
ekmConnectionBuilder_.mergeFrom(value);
}
if (ekmConnection_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEkmConnection() {
bitField0_ = (bitField0_ & ~0x00000004);
ekmConnection_ = null;
if (ekmConnectionBuilder_ != null) {
ekmConnectionBuilder_.dispose();
ekmConnectionBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.kms.v1.EkmConnection.Builder getEkmConnectionBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getEkmConnectionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.kms.v1.EkmConnectionOrBuilder getEkmConnectionOrBuilder() {
if (ekmConnectionBuilder_ != null) {
return ekmConnectionBuilder_.getMessageOrBuilder();
} else {
return ekmConnection_ == null
? com.google.cloud.kms.v1.EkmConnection.getDefaultInstance()
: ekmConnection_;
}
}
/**
*
*
* <pre>
* Required. An [EkmConnection][google.cloud.kms.v1.EkmConnection] with
* initial field values.
* </pre>
*
* <code>
* .google.cloud.kms.v1.EkmConnection ekm_connection = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.kms.v1.EkmConnection,
com.google.cloud.kms.v1.EkmConnection.Builder,
com.google.cloud.kms.v1.EkmConnectionOrBuilder>
getEkmConnectionFieldBuilder() {
if (ekmConnectionBuilder_ == null) {
ekmConnectionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.kms.v1.EkmConnection,
com.google.cloud.kms.v1.EkmConnection.Builder,
com.google.cloud.kms.v1.EkmConnectionOrBuilder>(
getEkmConnection(), getParentForChildren(), isClean());
ekmConnection_ = null;
}
return ekmConnectionBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.kms.v1.CreateEkmConnectionRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.kms.v1.CreateEkmConnectionRequest)
private static final com.google.cloud.kms.v1.CreateEkmConnectionRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.kms.v1.CreateEkmConnectionRequest();
}
public static com.google.cloud.kms.v1.CreateEkmConnectionRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateEkmConnectionRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateEkmConnectionRequest>() {
@java.lang.Override
public CreateEkmConnectionRequest 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<CreateEkmConnectionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateEkmConnectionRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.kms.v1.CreateEkmConnectionRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,078 | java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/CreateSessionEntityTypeRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/session_entity_type.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.v2beta1;
/**
*
*
* <pre>
* The request message for
* [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest}
*/
public final class CreateSessionEntityTypeRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest)
CreateSessionEntityTypeRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateSessionEntityTypeRequest.newBuilder() to construct.
private CreateSessionEntityTypeRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateSessionEntityTypeRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateSessionEntityTypeRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_CreateSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 SESSION_ENTITY_TYPE_FIELD_NUMBER = 2;
private com.google.cloud.dialogflow.v2beta1.SessionEntityType sessionEntityType_;
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sessionEntityType field is set.
*/
@java.lang.Override
public boolean hasSessionEntityType() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sessionEntityType.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.SessionEntityType getSessionEntityType() {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.v2beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.SessionEntityTypeOrBuilder
getSessionEntityTypeOrBuilder() {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.v2beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
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, getSessionEntityType());
}
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, getSessionEntityType());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest other =
(com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasSessionEntityType() != other.hasSessionEntityType()) return false;
if (hasSessionEntityType()) {
if (!getSessionEntityType().equals(other.getSessionEntityType())) 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 (hasSessionEntityType()) {
hash = (37 * hash) + SESSION_ENTITY_TYPE_FIELD_NUMBER;
hash = (53 * hash) + getSessionEntityType().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request message for
* [SessionEntityTypes.CreateSessionEntityType][google.cloud.dialogflow.v2beta1.SessionEntityTypes.CreateSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest)
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_CreateSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest.Builder.class);
}
// Construct using
// com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getSessionEntityTypeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
sessionEntityType_ = null;
if (sessionEntityTypeBuilder_ != null) {
sessionEntityTypeBuilder_.dispose();
sessionEntityTypeBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2beta1.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_CreateSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest build() {
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest buildPartial() {
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest result =
new com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.sessionEntityType_ =
sessionEntityTypeBuilder_ == null
? sessionEntityType_
: sessionEntityTypeBuilder_.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.dialogflow.v2beta1.CreateSessionEntityTypeRequest) {
return mergeFrom(
(com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest other) {
if (other
== com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasSessionEntityType()) {
mergeSessionEntityType(other.getSessionEntityType());
}
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(
getSessionEntityTypeFieldBuilder().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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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 session to create a session entity type for.
* Supported formats:
* - `projects/<Project ID>/agent/sessions/<Session ID>,
* - `projects/<Project ID>/locations/<Location ID>/agent/sessions/<Session
* ID>`,
* - `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
* ID>/sessions/<Session ID>`,
* - `projects/<Project ID>/locations/<Location
* ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session
* ID>`,
*
* If `Location ID` is not specified we assume default 'us' location. If
* `Environment ID` is not specified, we assume default 'draft' environment.
* If `User ID` is not specified, we assume default '-' user.
* </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.dialogflow.v2beta1.SessionEntityType sessionEntityType_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.SessionEntityType,
com.google.cloud.dialogflow.v2beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.v2beta1.SessionEntityTypeOrBuilder>
sessionEntityTypeBuilder_;
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sessionEntityType field is set.
*/
public boolean hasSessionEntityType() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sessionEntityType.
*/
public com.google.cloud.dialogflow.v2beta1.SessionEntityType getSessionEntityType() {
if (sessionEntityTypeBuilder_ == null) {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.v2beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
} else {
return sessionEntityTypeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSessionEntityType(
com.google.cloud.dialogflow.v2beta1.SessionEntityType value) {
if (sessionEntityTypeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
sessionEntityType_ = value;
} else {
sessionEntityTypeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSessionEntityType(
com.google.cloud.dialogflow.v2beta1.SessionEntityType.Builder builderForValue) {
if (sessionEntityTypeBuilder_ == null) {
sessionEntityType_ = builderForValue.build();
} else {
sessionEntityTypeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeSessionEntityType(
com.google.cloud.dialogflow.v2beta1.SessionEntityType value) {
if (sessionEntityTypeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& sessionEntityType_ != null
&& sessionEntityType_
!= com.google.cloud.dialogflow.v2beta1.SessionEntityType.getDefaultInstance()) {
getSessionEntityTypeBuilder().mergeFrom(value);
} else {
sessionEntityType_ = value;
}
} else {
sessionEntityTypeBuilder_.mergeFrom(value);
}
if (sessionEntityType_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearSessionEntityType() {
bitField0_ = (bitField0_ & ~0x00000002);
sessionEntityType_ = null;
if (sessionEntityTypeBuilder_ != null) {
sessionEntityTypeBuilder_.dispose();
sessionEntityTypeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.v2beta1.SessionEntityType.Builder
getSessionEntityTypeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getSessionEntityTypeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.v2beta1.SessionEntityTypeOrBuilder
getSessionEntityTypeOrBuilder() {
if (sessionEntityTypeBuilder_ != null) {
return sessionEntityTypeBuilder_.getMessageOrBuilder();
} else {
return sessionEntityType_ == null
? com.google.cloud.dialogflow.v2beta1.SessionEntityType.getDefaultInstance()
: sessionEntityType_;
}
}
/**
*
*
* <pre>
* Required. The session entity type to create.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.SessionEntityType session_entity_type = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.SessionEntityType,
com.google.cloud.dialogflow.v2beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.v2beta1.SessionEntityTypeOrBuilder>
getSessionEntityTypeFieldBuilder() {
if (sessionEntityTypeBuilder_ == null) {
sessionEntityTypeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.SessionEntityType,
com.google.cloud.dialogflow.v2beta1.SessionEntityType.Builder,
com.google.cloud.dialogflow.v2beta1.SessionEntityTypeOrBuilder>(
getSessionEntityType(), getParentForChildren(), isClean());
sessionEntityType_ = null;
}
return sessionEntityTypeBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest)
private static final com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest();
}
public static com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateSessionEntityTypeRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateSessionEntityTypeRequest>() {
@java.lang.Override
public CreateSessionEntityTypeRequest 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<CreateSessionEntityTypeRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateSessionEntityTypeRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.CreateSessionEntityTypeRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ignite | 37,909 | modules/binary/impl/src/main/java/org/apache/ignite/internal/marshaller/optimized/OptimizedObjectInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.marshaller.optimized;
import java.io.Externalizable;
import java.io.IOException;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectStreamClass;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.util.CommonUtils;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.io.GridDataInput;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.marshaller.MarshallerContext;
import org.apache.ignite.marshaller.Marshallers;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.ARRAY_LIST;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.BOOLEAN;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.BOOLEAN_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.BYTE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.BYTE_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.CHAR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.CHAR_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.CLS;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.DATE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.DOUBLE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.DOUBLE_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.ENUM;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.EXTERNALIZABLE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.FLOAT;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.FLOAT_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.HANDLE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.HASH_MAP;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.HASH_SET;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.HASH_SET_MAP_OFF;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.INT;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.INT_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.JDK;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.LINKED_HASH_MAP;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.LINKED_HASH_SET;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.LINKED_LIST;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.LONG;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.LONG_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.NULL;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.OBJ_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.PROPS;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.PROXY;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.SERIALIZABLE;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.SHORT;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.SHORT_ARR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.STR;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.UUID;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.classDescriptor;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setBoolean;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setByte;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setChar;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setDouble;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setFloat;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setInt;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setLong;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setObject;
import static org.apache.ignite.internal.marshaller.optimized.OptimizedMarshallerUtils.setShort;
/**
* Optimized object input stream.
*/
class OptimizedObjectInputStream extends ObjectInputStream {
/** Dummy object for HashSet. */
private static final Object DUMMY = new Object();
/** */
private final HandleTable handles = new HandleTable(10);
/** */
private MarshallerContext ctx;
/** */
private OptimizedMarshallerIdMapper mapper;
/** */
private ClassLoader clsLdr;
/** */
private GridDataInput in;
/** */
private Object curObj;
/** */
private OptimizedClassDescriptor.ClassFields curFields;
/** */
private Class<?> curCls;
/** */
private ConcurrentMap<Class, OptimizedClassDescriptor> clsMap;
/** The flag shown, the reader uses class loader cache used or not. */
private boolean useCache;
/**
* @param in Input.
* @throws IOException In case of error.
*/
OptimizedObjectInputStream(GridDataInput in) throws IOException {
this.in = in;
this.useCache = true;
}
/**
* @param clsMap Class descriptors by class map.
* @param ctx Context.
* @param mapper ID mapper.
* @param clsLdr Class loader.
* @param useCache True if class loader cache will be used, false otherwise.
*/
void context(
ConcurrentMap<Class, OptimizedClassDescriptor> clsMap,
MarshallerContext ctx,
OptimizedMarshallerIdMapper mapper,
ClassLoader clsLdr,
boolean useCache
) {
this.clsMap = clsMap;
this.ctx = ctx;
this.mapper = mapper;
this.clsLdr = clsLdr;
this.useCache = useCache;
}
/**
* @return Input.
*/
public GridDataInput in() {
return in;
}
/**
* @param in Input.
*/
public void in(GridDataInput in) {
this.in = in;
}
/** {@inheritDoc} */
@Override public void close() throws IOException {
reset();
ctx = null;
clsLdr = null;
clsMap = null;
}
/** {@inheritDoc} */
@SuppressWarnings("NonSynchronizedMethodOverridesSynchronizedMethod")
@Override public void reset() throws IOException {
in.reset();
handles.clear();
curObj = null;
curFields = null;
}
/** {@inheritDoc} */
@Override public Object readObjectOverride() throws ClassNotFoundException, IOException {
Object oldObj = curObj;
OptimizedClassDescriptor.ClassFields oldFields = curFields;
try {
return readObject0();
}
finally {
curObj = oldObj;
curFields = oldFields;
}
}
/**
* Reads object from stream.
*
* @return Object.
* @throws ClassNotFoundException If class was not found.
* @throws IOException In case of error.
*/
private Object readObject0() throws ClassNotFoundException, IOException {
curObj = null;
curFields = null;
byte ref = in.readByte();
switch (ref) {
case NULL:
return null;
case HANDLE:
return handles.lookup(readInt());
case JDK:
try {
return ctx.jdkMarshaller().unmarshal(this, clsLdr);
}
catch (IgniteCheckedException e) {
IOException ioEx = e.getCause(IOException.class);
if (ioEx != null)
throw ioEx;
else
throw new IOException("Failed to deserialize object with JDK marshaller.", e);
}
case BYTE:
return readByte();
case SHORT:
return readShort();
case INT:
return readInt();
case LONG:
return readLong();
case FLOAT:
return readFloat();
case DOUBLE:
return readDouble();
case CHAR:
return readChar();
case BOOLEAN:
return readBoolean();
case BYTE_ARR:
return readByteArray();
case SHORT_ARR:
return readShortArray();
case INT_ARR:
return readIntArray();
case LONG_ARR:
return readLongArray();
case FLOAT_ARR:
return readFloatArray();
case DOUBLE_ARR:
return readDoubleArray();
case CHAR_ARR:
return readCharArray();
case BOOLEAN_ARR:
return readBooleanArray();
case OBJ_ARR:
return readArray(readClass());
case STR:
return readString();
case UUID:
return readUuid();
case PROPS:
return readProperties();
case ARRAY_LIST:
return readArrayList();
case HASH_MAP:
return readHashMap(false);
case HASH_SET:
return readHashSet(HASH_SET_MAP_OFF);
case LINKED_LIST:
return readLinkedList();
case LINKED_HASH_MAP:
return readLinkedHashMap(false);
case LINKED_HASH_SET:
return readLinkedHashSet(HASH_SET_MAP_OFF);
case DATE:
return readDate();
case CLS:
return readClass();
case PROXY:
Class<?>[] intfs = new Class<?>[readInt()];
for (int i = 0; i < intfs.length; i++)
intfs[i] = readClass();
InvocationHandler ih = (InvocationHandler)readObject();
return Proxy.newProxyInstance(clsLdr != null ? clsLdr : CommonUtils.gridClassLoader(), intfs, ih);
case ENUM:
case EXTERNALIZABLE:
case SERIALIZABLE:
int typeId = readInt();
OptimizedClassDescriptor desc = typeId == 0
? classDescriptor(
clsMap,
CommonUtils.forName(readUTF(), clsLdr, ctx.classNameFilter(), useCache),
useCache,
ctx,
mapper)
: classDescriptor(clsMap, typeId, clsLdr, useCache, ctx, mapper);
curCls = desc.describedClass();
try {
return desc.read(this);
}
catch (IOException e) {
throw new IOException("Failed to deserialize object [typeName=" +
desc.describedClass().getName() + ']', e);
}
default:
SB msg = new SB("Unexpected error occurred during unmarshalling");
if (curCls != null)
msg.a(" of an instance of the class: ").a(curCls.getName());
msg.a(". Check that all nodes are running the same version of Ignite and that all nodes have " +
"GridOptimizedMarshaller configured with identical optimized classes lists, if any " +
"(see setClassNames and setClassNamesPath methods). If your serialized classes implement " +
"java.io.Externalizable interface, verify that serialization logic is correct.");
throw new IOException(msg.toString());
}
}
/**
* @return Class.
* @throws ClassNotFoundException If class was not found.
* @throws IOException In case of other error.
*/
private Class<?> readClass() throws ClassNotFoundException, IOException {
int compTypeId = readInt();
return compTypeId == 0 ? CommonUtils.forName(readUTF(), clsLdr, null, useCache) :
classDescriptor(clsMap, compTypeId, clsLdr, useCache, ctx, mapper).describedClass();
}
/**
* Reads array from this stream.
*
* @param compType Array component type.
* @return Array.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
<T> T[] readArray(Class<T> compType) throws ClassNotFoundException, IOException {
int len = in.readInt();
T[] arr = (T[])Array.newInstance(compType, len);
handles.assign(arr);
for (int i = 0; i < len; i++)
arr[i] = (T)readObject();
return arr;
}
/**
* Reads {@link UUID} from this stream.
*
* @return UUID.
* @throws IOException In case of error.
*/
UUID readUuid() throws IOException {
UUID uuid = new UUID(readLong(), readLong());
handles.assign(uuid);
return uuid;
}
/**
* Reads {@link Properties} from this stream.
*
* @return Properties.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
Properties readProperties() throws ClassNotFoundException, IOException {
Properties dflts = readBoolean() ? null : (Properties)readObject();
Properties props = new Properties(dflts);
int size = in.readInt();
for (int i = 0; i < size; i++)
props.setProperty(readUTF(), readUTF());
handles.assign(props);
return props;
}
/**
* Reads and sets all non-static and non-transient field values from this stream.
*
* @param obj Object.
* @param fieldOffs Field offsets.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
void readFields(Object obj, OptimizedClassDescriptor.ClassFields fieldOffs) throws ClassNotFoundException,
IOException {
for (int i = 0; i < fieldOffs.size(); i++) {
OptimizedClassDescriptor.FieldInfo t = fieldOffs.get(i);
try {
switch ((t.type())) {
case BYTE:
byte resByte = readByte();
if (t.field() != null)
setByte(obj, t.offset(), resByte);
break;
case SHORT:
short resShort = readShort();
if (t.field() != null)
setShort(obj, t.offset(), resShort);
break;
case INT:
int resInt = readInt();
if (t.field() != null)
setInt(obj, t.offset(), resInt);
break;
case LONG:
long resLong = readLong();
if (t.field() != null)
setLong(obj, t.offset(), resLong);
break;
case FLOAT:
float resFloat = readFloat();
if (t.field() != null)
setFloat(obj, t.offset(), resFloat);
break;
case DOUBLE:
double resDouble = readDouble();
if (t.field() != null)
setDouble(obj, t.offset(), resDouble);
break;
case CHAR:
char resChar = readChar();
if (t.field() != null)
setChar(obj, t.offset(), resChar);
break;
case BOOLEAN:
boolean resBoolean = readBoolean();
if (t.field() != null)
setBoolean(obj, t.offset(), resBoolean);
break;
case OTHER:
Object resObj = readObject();
if (t.field() != null)
setObject(obj, t.offset(), resObj);
}
}
catch (IOException e) {
throw new IOException("Failed to deserialize field [name=" + t.name() + ']', e);
}
}
}
/** {@inheritDoc} */
@Override protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
// NOTE: DO NOT CHANGE TO 'clsLoader.loadClass()'
// Must have 'Class.forName()' instead of clsLoader.loadClass()
// due to weird ClassNotFoundExceptions for arrays of classes
// in certain cases.
return CommonUtils.forName(desc.getName(), clsLdr, ctx.classNameFilter(), Marshallers.USE_CACHE.get());
}
/**
* Reads {@link Externalizable} object.
*
* @param constructor Constructor.
* @param readResolveMtd {@code readResolve} method.
* @return Object.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
Object readExternalizable(Constructor<?> constructor, Method readResolveMtd)
throws ClassNotFoundException, IOException {
Object obj;
try {
obj = constructor.newInstance();
}
catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
throw new IOException(e);
}
int handle = handles.assign(obj);
Externalizable extObj = ((Externalizable)obj);
extObj.readExternal(this);
if (readResolveMtd != null) {
try {
obj = readResolveMtd.invoke(obj);
handles.set(handle, obj);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IOException(e);
}
}
return obj;
}
/**
* Reads serializable object.
*
* @param cls Class.
* @param mtds {@code readObject} methods.
* @param readResolveMtd {@code readResolve} method.
* @param fields class fields details.
* @return Object.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
Object readSerializable(Class<?> cls, List<Method> mtds, Method readResolveMtd,
OptimizedClassDescriptor.Fields fields) throws ClassNotFoundException, IOException {
Object obj;
try {
obj = GridUnsafe.allocateInstance(cls);
}
catch (InstantiationException e) {
throw new IOException(e);
}
int handle = handles.assign(obj);
for (int i = 0; i < mtds.size(); i++) {
Method mtd = mtds.get(i);
if (mtd != null) {
curObj = obj;
curFields = fields.fields(i);
try {
mtd.invoke(obj, this);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IOException(e);
}
}
else
readFields(obj, fields.fields(i));
}
if (readResolveMtd != null) {
try {
obj = readResolveMtd.invoke(obj);
handles.set(handle, obj);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IOException(e);
}
}
return obj;
}
/**
* Reads {@link ArrayList}.
*
* @return List.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
ArrayList<?> readArrayList() throws ClassNotFoundException, IOException {
int size = readInt();
ArrayList<Object> list = new ArrayList<>(size);
handles.assign(list);
for (int i = 0; i < size; i++)
list.add(readObject());
return list;
}
/**
* Reads {@link HashMap}.
*
* @param set Whether reading underlying map from {@link HashSet}.
* @return Map.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
HashMap<?, ?> readHashMap(boolean set) throws ClassNotFoundException, IOException {
int size = readInt();
float loadFactor = readFloat();
HashMap<Object, Object> map = new HashMap<>(size, loadFactor);
if (!set)
handles.assign(map);
for (int i = 0; i < size; i++) {
Object key = readObject();
Object val = !set ? readObject() : DUMMY;
map.put(key, val);
}
return map;
}
/**
* Reads {@link HashSet}.
*
* @param mapFieldOff Map field offset.
* @return Set.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
HashSet<?> readHashSet(long mapFieldOff) throws ClassNotFoundException, IOException {
try {
HashSet<Object> set = (HashSet<Object>)GridUnsafe.allocateInstance(HashSet.class);
handles.assign(set);
setObject(set, mapFieldOff, readHashMap(true));
return set;
}
catch (InstantiationException e) {
throw new IOException(e);
}
}
/**
* Reads {@link LinkedList}.
*
* @return List.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
LinkedList<?> readLinkedList() throws ClassNotFoundException, IOException {
int size = readInt();
LinkedList<Object> list = new LinkedList<>();
handles.assign(list);
for (int i = 0; i < size; i++)
list.add(readObject());
return list;
}
/**
* Reads {@link LinkedHashMap}.
*
* @param set Whether reading underlying map from {@link LinkedHashSet}.
* @return Map.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
LinkedHashMap<?, ?> readLinkedHashMap(boolean set) throws ClassNotFoundException, IOException {
int size = readInt();
float loadFactor = readFloat();
boolean accessOrder = readBoolean();
LinkedHashMap<Object, Object> map = new LinkedHashMap<>(size, loadFactor, accessOrder);
if (!set)
handles.assign(map);
for (int i = 0; i < size; i++) {
Object key = readObject();
Object val = !set ? readObject() : DUMMY;
map.put(key, val);
}
return map;
}
/**
* Reads {@link LinkedHashSet}.
*
* @param mapFieldOff Map field offset.
* @return Set.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
LinkedHashSet<?> readLinkedHashSet(long mapFieldOff) throws ClassNotFoundException, IOException {
try {
LinkedHashSet<Object> set = (LinkedHashSet<Object>)GridUnsafe.allocateInstance(LinkedHashSet.class);
handles.assign(set);
setObject(set, mapFieldOff, readLinkedHashMap(true));
return set;
}
catch (InstantiationException e) {
throw new IOException(e);
}
}
/**
* Reads {@link Date}.
*
* @return Date.
* @throws ClassNotFoundException If class not found.
* @throws IOException In case of error.
*/
Date readDate() throws ClassNotFoundException, IOException {
Date date = new Date(readLong());
handles.assign(date);
return date;
}
/**
* Reads array of {@code byte}s.
*
* @return Array.
* @throws IOException In case of error.
*/
byte[] readByteArray() throws IOException {
byte[] arr = in.readByteArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code short}s.
*
* @return Array.
* @throws IOException In case of error.
*/
short[] readShortArray() throws IOException {
short[] arr = in.readShortArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code int}s.
*
* @return Array.
* @throws IOException In case of error.
*/
int[] readIntArray() throws IOException {
int[] arr = in.readIntArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code long}s.
*
* @return Array.
* @throws IOException In case of error.
*/
long[] readLongArray() throws IOException {
long[] arr = in.readLongArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code float}s.
*
* @return Array.
* @throws IOException In case of error.
*/
float[] readFloatArray() throws IOException {
float[] arr = in.readFloatArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code double}s.
*
* @return Array.
* @throws IOException In case of error.
*/
double[] readDoubleArray() throws IOException {
double[] arr = in.readDoubleArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code char}s.
*
* @return Array.
* @throws IOException In case of error.
*/
char[] readCharArray() throws IOException {
char[] arr = in.readCharArray();
handles.assign(arr);
return arr;
}
/**
* Reads array of {@code boolean}s.
*
* @return Array.
* @throws IOException In case of error.
*/
boolean[] readBooleanArray() throws IOException {
boolean[] arr = in.readBooleanArray();
handles.assign(arr);
return arr;
}
/**
* Reads {@link String}.
*
* @return String.
* @throws IOException In case of error.
*/
public String readString() throws IOException {
String str = in.readUTF();
handles.assign(str);
return str;
}
/** {@inheritDoc} */
@Override public void readFully(byte[] b) throws IOException {
in.readFully(b);
}
/** {@inheritDoc} */
@Override public void readFully(byte[] b, int off, int len) throws IOException {
in.readFully(b, off, len);
}
/** {@inheritDoc} */
@Override public int skipBytes(int n) throws IOException {
return in.skipBytes(n);
}
/** {@inheritDoc} */
@Override public boolean readBoolean() throws IOException {
return in.readBoolean();
}
/** {@inheritDoc} */
@Override public byte readByte() throws IOException {
return in.readByte();
}
/** {@inheritDoc} */
@Override public int readUnsignedByte() throws IOException {
return in.readUnsignedByte();
}
/** {@inheritDoc} */
@Override public short readShort() throws IOException {
return in.readShort();
}
/** {@inheritDoc} */
@Override public int readUnsignedShort() throws IOException {
return in.readUnsignedShort();
}
/** {@inheritDoc} */
@Override public char readChar() throws IOException {
return in.readChar();
}
/** {@inheritDoc} */
@Override public int readInt() throws IOException {
return in.readInt();
}
/** {@inheritDoc} */
@Override public long readLong() throws IOException {
return in.readLong();
}
/** {@inheritDoc} */
@Override public float readFloat() throws IOException {
return in.readFloat();
}
/** {@inheritDoc} */
@Override public double readDouble() throws IOException {
return in.readDouble();
}
/** {@inheritDoc} */
@Override public int read() throws IOException {
return in.read();
}
/** {@inheritDoc} */
@Override public int read(byte[] b) throws IOException {
return in.read(b);
}
/** {@inheritDoc} */
@Override public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override public String readLine() throws IOException {
return in.readLine();
}
/** {@inheritDoc} */
@Override public String readUTF() throws IOException {
return in.readUTF();
}
/** {@inheritDoc} */
@Override public Object readUnshared() throws IOException, ClassNotFoundException {
return readObject();
}
/** {@inheritDoc} */
@Override public void defaultReadObject() throws IOException, ClassNotFoundException {
if (curObj == null)
throw new NotActiveException("Not in readObject() call.");
readFields(curObj, curFields);
}
/** {@inheritDoc} */
@Override public ObjectInputStream.GetField readFields() throws IOException, ClassNotFoundException {
if (curObj == null)
throw new NotActiveException("Not in readObject() call.");
return new GetFieldImpl(this);
}
/** {@inheritDoc} */
@Override public void registerValidation(ObjectInputValidation obj, int pri) {
// No-op.
}
/** {@inheritDoc} */
@Override public int available() throws IOException {
return -1;
}
/**
* Returns objects that were added to handles table.
* Used ONLY for test purposes.
*
* @return Handled objects.
*/
Object[] handledObjects() {
return handles.entries;
}
/**
* Lightweight identity hash table which maps objects to integer handles,
* assigned in ascending order.
*/
private static class HandleTable {
/** Array mapping handle -> object/exception (depending on status). */
private Object[] entries;
/** Number of handles in table. */
private int size;
/**
* Creates handle table with the given initial capacity.
*
* @param initCap Initial capacity.
*/
HandleTable(int initCap) {
entries = new Object[initCap];
}
/**
* Assigns next available handle to given object, and returns assigned
* handle.
*
* @param obj Object.
* @return Handle.
*/
int assign(Object obj) {
if (size >= entries.length)
grow();
entries[size] = obj;
return size++;
}
/**
* Assigns new object to existing handle. Old object is forgotten.
*
* @param handle Handle.
* @param obj Object.
*/
void set(int handle, Object obj) {
entries[handle] = obj;
}
/**
* Looks up and returns object associated with the given handle.
*
* @param handle Handle.
* @return Object.
*/
Object lookup(int handle) {
return entries[handle];
}
/**
* Resets table to its initial state.
*/
void clear() {
Arrays.fill(entries, 0, size, null);
size = 0;
}
/**
* Expands capacity of internal arrays.
*/
private void grow() {
int newCap = (entries.length << 1) + 1;
Object[] newEntries = new Object[newCap];
System.arraycopy(entries, 0, newEntries, 0, size);
entries = newEntries;
}
}
/**
* {@link GetField} implementation.
*/
private static class GetFieldImpl extends GetField {
/** Field info. */
private final OptimizedClassDescriptor.ClassFields fieldInfo;
/** Values. */
private final Object[] objs;
/**
* @param in Stream.
* @throws IOException In case of error.
* @throws ClassNotFoundException If class not found.
*/
private GetFieldImpl(OptimizedObjectInputStream in) throws IOException, ClassNotFoundException {
fieldInfo = in.curFields;
objs = new Object[fieldInfo.size()];
for (int i = 0; i < fieldInfo.size(); i++) {
OptimizedClassDescriptor.FieldInfo t = fieldInfo.get(i);
Object obj = null;
switch (t.type()) {
case BYTE:
obj = in.readByte();
break;
case SHORT:
obj = in.readShort();
break;
case INT:
obj = in.readInt();
break;
case LONG:
obj = in.readLong();
break;
case FLOAT:
obj = in.readFloat();
break;
case DOUBLE:
obj = in.readDouble();
break;
case CHAR:
obj = in.readChar();
break;
case BOOLEAN:
obj = in.readBoolean();
break;
case OTHER:
obj = in.readObject();
}
objs[i] = obj;
}
}
/** {@inheritDoc} */
@Override public ObjectStreamClass getObjectStreamClass() {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public boolean defaulted(String name) throws IOException {
return objs[fieldInfo.getIndex(name)] == null;
}
/** {@inheritDoc} */
@Override public boolean get(String name, boolean dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public byte get(String name, byte dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public char get(String name, char dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public short get(String name, short dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public int get(String name, int dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public long get(String name, long dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public float get(String name, float dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public double get(String name, double dflt) throws IOException {
return value(name, dflt);
}
/** {@inheritDoc} */
@Override public Object get(String name, Object dflt) throws IOException {
return value(name, dflt);
}
/**
* @param name Field name.
* @param dflt Default value.
* @return Value.
*/
private <T> T value(String name, T dflt) {
return objs[fieldInfo.getIndex(name)] != null ? (T)objs[fieldInfo.getIndex(name)] : dflt;
}
}
}
|
googleapis/google-api-java-client-services | 38,093 | clients/google-api-services-testing/v1/1.26.0/com/google/api/services/testing/Testing.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.testing;
/**
* Service definition for Testing (v1).
*
* <p>
* Allows developers to run automated tests for their mobile applications on Google infrastructure.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/cloud-test-lab/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link TestingRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Testing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.26.0 of the Cloud Testing 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://testing.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 Testing(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
*/
Testing(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 ApplicationDetailService collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.ApplicationDetailService.List request = testing.applicationDetailService().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public ApplicationDetailService applicationDetailService() {
return new ApplicationDetailService();
}
/**
* The "applicationDetailService" collection of methods.
*/
public class ApplicationDetailService {
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @return the request
*/
public GetApkDetails getApkDetails(com.google.api.services.testing.model.FileReference content) throws java.io.IOException {
GetApkDetails result = new GetApkDetails(content);
initialize(result);
return result;
}
public class GetApkDetails extends TestingRequest<com.google.api.services.testing.model.GetApkDetailsResponse> {
private static final String REST_PATH = "v1/applicationDetailService/getApkDetails";
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. <p>
* {@link GetApkDetails#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR
* equest)} must be called to initialize this instance immediately after invoking the constructor.
* </p>
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @since 1.13
*/
protected GetApkDetails(com.google.api.services.testing.model.FileReference content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.GetApkDetailsResponse.class);
}
@Override
public GetApkDetails set$Xgafv(java.lang.String $Xgafv) {
return (GetApkDetails) super.set$Xgafv($Xgafv);
}
@Override
public GetApkDetails setAccessToken(java.lang.String accessToken) {
return (GetApkDetails) super.setAccessToken(accessToken);
}
@Override
public GetApkDetails setAlt(java.lang.String alt) {
return (GetApkDetails) super.setAlt(alt);
}
@Override
public GetApkDetails setCallback(java.lang.String callback) {
return (GetApkDetails) super.setCallback(callback);
}
@Override
public GetApkDetails setFields(java.lang.String fields) {
return (GetApkDetails) super.setFields(fields);
}
@Override
public GetApkDetails setKey(java.lang.String key) {
return (GetApkDetails) super.setKey(key);
}
@Override
public GetApkDetails setOauthToken(java.lang.String oauthToken) {
return (GetApkDetails) super.setOauthToken(oauthToken);
}
@Override
public GetApkDetails setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetApkDetails) super.setPrettyPrint(prettyPrint);
}
@Override
public GetApkDetails setQuotaUser(java.lang.String quotaUser) {
return (GetApkDetails) super.setQuotaUser(quotaUser);
}
@Override
public GetApkDetails setUploadType(java.lang.String uploadType) {
return (GetApkDetails) super.setUploadType(uploadType);
}
@Override
public GetApkDetails setUploadProtocol(java.lang.String uploadProtocol) {
return (GetApkDetails) super.setUploadProtocol(uploadProtocol);
}
@Override
public GetApkDetails set(String parameterName, Object value) {
return (GetApkDetails) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.Projects.List request = testing.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the TestMatrices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestMatrices.List request = testing.testMatrices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestMatrices testMatrices() {
return new TestMatrices();
}
/**
* The "testMatrices" collection of methods.
*/
public class TestMatrices {
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have no
* effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @return the request
*/
public Cancel cancel(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Cancel result = new Cancel(projectId, testMatrixId);
initialize(result);
return result;
}
public class Cancel extends TestingRequest<com.google.api.services.testing.model.CancelTestMatrixResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}:cancel";
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have
* no effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @since 1.13
*/
protected Cancel(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "POST", REST_PATH, null, com.google.api.services.testing.model.CancelTestMatrixResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified.");
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/** Cloud project that owns the test. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test. */
public Cancel setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Test matrix that will be canceled. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Test matrix that will be canceled.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Test matrix that will be canceled. */
public Cancel setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200 supported
* executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @return the request
*/
public Create create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) throws java.io.IOException {
Create result = new Create(projectId, content);
initialize(result);
return result;
}
public class Create extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices";
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200
* supported executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @since 1.13
*/
protected Create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** The GCE project under which this job will run. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** The GCE project under which this job will run.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** The GCE project under which this job will run. */
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
@com.google.api.client.util.Key
private java.lang.String requestId;
/** A string id used to detect duplicated requests. Ids are automatically scoped to a project, so users
should ensure the ID is unique per-project. A UUID is recommended.
Optional, but strongly recommended.
*/
public java.lang.String getRequestId() {
return requestId;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
public Create setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Get result = new Get(projectId, testMatrixId);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}";
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the the testing 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 Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId 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);
}
/** Cloud project that owns the test matrix. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test matrix.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test matrix. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Unique test matrix id which was assigned by the service. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Unique test matrix id which was assigned by the service.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Unique test matrix id which was assigned by the service. */
public Get setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the TestEnvironmentCatalog collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestEnvironmentCatalog.List request = testing.testEnvironmentCatalog().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestEnvironmentCatalog testEnvironmentCatalog() {
return new TestEnvironmentCatalog();
}
/**
* The "testEnvironmentCatalog" collection of methods.
*/
public class TestEnvironmentCatalog {
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param environmentType Required. The type of environment that should be listed.
* @return the request
*/
public Get get(java.lang.String environmentType) throws java.io.IOException {
Get result = new Get(environmentType);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestEnvironmentCatalog> {
private static final String REST_PATH = "v1/testEnvironmentCatalog/{environmentType}";
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the the testing 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 environmentType Required. The type of environment that should be listed.
* @since 1.13
*/
protected Get(java.lang.String environmentType) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestEnvironmentCatalog.class);
this.environmentType = com.google.api.client.util.Preconditions.checkNotNull(environmentType, "Required parameter environmentType 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. The type of environment that should be listed. */
@com.google.api.client.util.Key
private java.lang.String environmentType;
/** Required. The type of environment that should be listed.
*/
public java.lang.String getEnvironmentType() {
return environmentType;
}
/** Required. The type of environment that should be listed. */
public Get setEnvironmentType(java.lang.String environmentType) {
this.environmentType = environmentType;
return this;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** For authorization, the cloud project requesting the TestEnvironmentCatalog.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Testing}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Testing}. */
@Override
public Testing build() {
return new Testing(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 TestingRequestInitializer}.
*
* @since 1.12
*/
public Builder setTestingRequestInitializer(
TestingRequestInitializer testingRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(testingRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-api-java-client-services | 38,093 | clients/google-api-services-testing/v1/1.27.0/com/google/api/services/testing/Testing.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.testing;
/**
* Service definition for Testing (v1).
*
* <p>
* Allows developers to run automated tests for their mobile applications on Google infrastructure.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/cloud-test-lab/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link TestingRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Testing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.27.0 of the Cloud Testing 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://testing.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 Testing(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
*/
Testing(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 ApplicationDetailService collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.ApplicationDetailService.List request = testing.applicationDetailService().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public ApplicationDetailService applicationDetailService() {
return new ApplicationDetailService();
}
/**
* The "applicationDetailService" collection of methods.
*/
public class ApplicationDetailService {
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @return the request
*/
public GetApkDetails getApkDetails(com.google.api.services.testing.model.FileReference content) throws java.io.IOException {
GetApkDetails result = new GetApkDetails(content);
initialize(result);
return result;
}
public class GetApkDetails extends TestingRequest<com.google.api.services.testing.model.GetApkDetailsResponse> {
private static final String REST_PATH = "v1/applicationDetailService/getApkDetails";
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. <p>
* {@link GetApkDetails#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR
* equest)} must be called to initialize this instance immediately after invoking the constructor.
* </p>
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @since 1.13
*/
protected GetApkDetails(com.google.api.services.testing.model.FileReference content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.GetApkDetailsResponse.class);
}
@Override
public GetApkDetails set$Xgafv(java.lang.String $Xgafv) {
return (GetApkDetails) super.set$Xgafv($Xgafv);
}
@Override
public GetApkDetails setAccessToken(java.lang.String accessToken) {
return (GetApkDetails) super.setAccessToken(accessToken);
}
@Override
public GetApkDetails setAlt(java.lang.String alt) {
return (GetApkDetails) super.setAlt(alt);
}
@Override
public GetApkDetails setCallback(java.lang.String callback) {
return (GetApkDetails) super.setCallback(callback);
}
@Override
public GetApkDetails setFields(java.lang.String fields) {
return (GetApkDetails) super.setFields(fields);
}
@Override
public GetApkDetails setKey(java.lang.String key) {
return (GetApkDetails) super.setKey(key);
}
@Override
public GetApkDetails setOauthToken(java.lang.String oauthToken) {
return (GetApkDetails) super.setOauthToken(oauthToken);
}
@Override
public GetApkDetails setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetApkDetails) super.setPrettyPrint(prettyPrint);
}
@Override
public GetApkDetails setQuotaUser(java.lang.String quotaUser) {
return (GetApkDetails) super.setQuotaUser(quotaUser);
}
@Override
public GetApkDetails setUploadType(java.lang.String uploadType) {
return (GetApkDetails) super.setUploadType(uploadType);
}
@Override
public GetApkDetails setUploadProtocol(java.lang.String uploadProtocol) {
return (GetApkDetails) super.setUploadProtocol(uploadProtocol);
}
@Override
public GetApkDetails set(String parameterName, Object value) {
return (GetApkDetails) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.Projects.List request = testing.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the TestMatrices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestMatrices.List request = testing.testMatrices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestMatrices testMatrices() {
return new TestMatrices();
}
/**
* The "testMatrices" collection of methods.
*/
public class TestMatrices {
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have no
* effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @return the request
*/
public Cancel cancel(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Cancel result = new Cancel(projectId, testMatrixId);
initialize(result);
return result;
}
public class Cancel extends TestingRequest<com.google.api.services.testing.model.CancelTestMatrixResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}:cancel";
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have
* no effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @since 1.13
*/
protected Cancel(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "POST", REST_PATH, null, com.google.api.services.testing.model.CancelTestMatrixResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified.");
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/** Cloud project that owns the test. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test. */
public Cancel setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Test matrix that will be canceled. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Test matrix that will be canceled.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Test matrix that will be canceled. */
public Cancel setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200 supported
* executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @return the request
*/
public Create create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) throws java.io.IOException {
Create result = new Create(projectId, content);
initialize(result);
return result;
}
public class Create extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices";
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200
* supported executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @since 1.13
*/
protected Create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** The GCE project under which this job will run. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** The GCE project under which this job will run.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** The GCE project under which this job will run. */
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
@com.google.api.client.util.Key
private java.lang.String requestId;
/** A string id used to detect duplicated requests. Ids are automatically scoped to a project, so users
should ensure the ID is unique per-project. A UUID is recommended.
Optional, but strongly recommended.
*/
public java.lang.String getRequestId() {
return requestId;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
public Create setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Get result = new Get(projectId, testMatrixId);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}";
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the the testing 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 Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId 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);
}
/** Cloud project that owns the test matrix. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test matrix.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test matrix. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Unique test matrix id which was assigned by the service. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Unique test matrix id which was assigned by the service.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Unique test matrix id which was assigned by the service. */
public Get setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the TestEnvironmentCatalog collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestEnvironmentCatalog.List request = testing.testEnvironmentCatalog().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestEnvironmentCatalog testEnvironmentCatalog() {
return new TestEnvironmentCatalog();
}
/**
* The "testEnvironmentCatalog" collection of methods.
*/
public class TestEnvironmentCatalog {
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param environmentType Required. The type of environment that should be listed.
* @return the request
*/
public Get get(java.lang.String environmentType) throws java.io.IOException {
Get result = new Get(environmentType);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestEnvironmentCatalog> {
private static final String REST_PATH = "v1/testEnvironmentCatalog/{environmentType}";
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the the testing 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 environmentType Required. The type of environment that should be listed.
* @since 1.13
*/
protected Get(java.lang.String environmentType) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestEnvironmentCatalog.class);
this.environmentType = com.google.api.client.util.Preconditions.checkNotNull(environmentType, "Required parameter environmentType 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. The type of environment that should be listed. */
@com.google.api.client.util.Key
private java.lang.String environmentType;
/** Required. The type of environment that should be listed.
*/
public java.lang.String getEnvironmentType() {
return environmentType;
}
/** Required. The type of environment that should be listed. */
public Get setEnvironmentType(java.lang.String environmentType) {
this.environmentType = environmentType;
return this;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** For authorization, the cloud project requesting the TestEnvironmentCatalog.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Testing}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Testing}. */
@Override
public Testing build() {
return new Testing(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 TestingRequestInitializer}.
*
* @since 1.12
*/
public Builder setTestingRequestInitializer(
TestingRequestInitializer testingRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(testingRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-api-java-client-services | 38,093 | clients/google-api-services-testing/v1/1.28.0/com/google/api/services/testing/Testing.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.testing;
/**
* Service definition for Testing (v1).
*
* <p>
* Allows developers to run automated tests for their mobile applications on Google infrastructure.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/cloud-test-lab/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link TestingRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Testing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.28.0 of the Cloud Testing 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://testing.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 Testing(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
*/
Testing(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 ApplicationDetailService collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.ApplicationDetailService.List request = testing.applicationDetailService().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public ApplicationDetailService applicationDetailService() {
return new ApplicationDetailService();
}
/**
* The "applicationDetailService" collection of methods.
*/
public class ApplicationDetailService {
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @return the request
*/
public GetApkDetails getApkDetails(com.google.api.services.testing.model.FileReference content) throws java.io.IOException {
GetApkDetails result = new GetApkDetails(content);
initialize(result);
return result;
}
public class GetApkDetails extends TestingRequest<com.google.api.services.testing.model.GetApkDetailsResponse> {
private static final String REST_PATH = "v1/applicationDetailService/getApkDetails";
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. <p>
* {@link GetApkDetails#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR
* equest)} must be called to initialize this instance immediately after invoking the constructor.
* </p>
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @since 1.13
*/
protected GetApkDetails(com.google.api.services.testing.model.FileReference content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.GetApkDetailsResponse.class);
}
@Override
public GetApkDetails set$Xgafv(java.lang.String $Xgafv) {
return (GetApkDetails) super.set$Xgafv($Xgafv);
}
@Override
public GetApkDetails setAccessToken(java.lang.String accessToken) {
return (GetApkDetails) super.setAccessToken(accessToken);
}
@Override
public GetApkDetails setAlt(java.lang.String alt) {
return (GetApkDetails) super.setAlt(alt);
}
@Override
public GetApkDetails setCallback(java.lang.String callback) {
return (GetApkDetails) super.setCallback(callback);
}
@Override
public GetApkDetails setFields(java.lang.String fields) {
return (GetApkDetails) super.setFields(fields);
}
@Override
public GetApkDetails setKey(java.lang.String key) {
return (GetApkDetails) super.setKey(key);
}
@Override
public GetApkDetails setOauthToken(java.lang.String oauthToken) {
return (GetApkDetails) super.setOauthToken(oauthToken);
}
@Override
public GetApkDetails setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetApkDetails) super.setPrettyPrint(prettyPrint);
}
@Override
public GetApkDetails setQuotaUser(java.lang.String quotaUser) {
return (GetApkDetails) super.setQuotaUser(quotaUser);
}
@Override
public GetApkDetails setUploadType(java.lang.String uploadType) {
return (GetApkDetails) super.setUploadType(uploadType);
}
@Override
public GetApkDetails setUploadProtocol(java.lang.String uploadProtocol) {
return (GetApkDetails) super.setUploadProtocol(uploadProtocol);
}
@Override
public GetApkDetails set(String parameterName, Object value) {
return (GetApkDetails) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.Projects.List request = testing.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the TestMatrices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestMatrices.List request = testing.testMatrices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestMatrices testMatrices() {
return new TestMatrices();
}
/**
* The "testMatrices" collection of methods.
*/
public class TestMatrices {
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have no
* effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @return the request
*/
public Cancel cancel(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Cancel result = new Cancel(projectId, testMatrixId);
initialize(result);
return result;
}
public class Cancel extends TestingRequest<com.google.api.services.testing.model.CancelTestMatrixResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}:cancel";
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have
* no effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @since 1.13
*/
protected Cancel(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "POST", REST_PATH, null, com.google.api.services.testing.model.CancelTestMatrixResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified.");
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/** Cloud project that owns the test. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test. */
public Cancel setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Test matrix that will be canceled. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Test matrix that will be canceled.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Test matrix that will be canceled. */
public Cancel setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200 supported
* executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @return the request
*/
public Create create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) throws java.io.IOException {
Create result = new Create(projectId, content);
initialize(result);
return result;
}
public class Create extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices";
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200
* supported executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @since 1.13
*/
protected Create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** The GCE project under which this job will run. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** The GCE project under which this job will run.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** The GCE project under which this job will run. */
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
@com.google.api.client.util.Key
private java.lang.String requestId;
/** A string id used to detect duplicated requests. Ids are automatically scoped to a project, so users
should ensure the ID is unique per-project. A UUID is recommended.
Optional, but strongly recommended.
*/
public java.lang.String getRequestId() {
return requestId;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
public Create setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Get result = new Get(projectId, testMatrixId);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}";
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the the testing 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 Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId 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);
}
/** Cloud project that owns the test matrix. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test matrix.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test matrix. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Unique test matrix id which was assigned by the service. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Unique test matrix id which was assigned by the service.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Unique test matrix id which was assigned by the service. */
public Get setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the TestEnvironmentCatalog collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestEnvironmentCatalog.List request = testing.testEnvironmentCatalog().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestEnvironmentCatalog testEnvironmentCatalog() {
return new TestEnvironmentCatalog();
}
/**
* The "testEnvironmentCatalog" collection of methods.
*/
public class TestEnvironmentCatalog {
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param environmentType Required. The type of environment that should be listed.
* @return the request
*/
public Get get(java.lang.String environmentType) throws java.io.IOException {
Get result = new Get(environmentType);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestEnvironmentCatalog> {
private static final String REST_PATH = "v1/testEnvironmentCatalog/{environmentType}";
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the the testing 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 environmentType Required. The type of environment that should be listed.
* @since 1.13
*/
protected Get(java.lang.String environmentType) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestEnvironmentCatalog.class);
this.environmentType = com.google.api.client.util.Preconditions.checkNotNull(environmentType, "Required parameter environmentType 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. The type of environment that should be listed. */
@com.google.api.client.util.Key
private java.lang.String environmentType;
/** Required. The type of environment that should be listed.
*/
public java.lang.String getEnvironmentType() {
return environmentType;
}
/** Required. The type of environment that should be listed. */
public Get setEnvironmentType(java.lang.String environmentType) {
this.environmentType = environmentType;
return this;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** For authorization, the cloud project requesting the TestEnvironmentCatalog.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Testing}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Testing}. */
@Override
public Testing build() {
return new Testing(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 TestingRequestInitializer}.
*
* @since 1.12
*/
public Builder setTestingRequestInitializer(
TestingRequestInitializer testingRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(testingRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-api-java-client-services | 38,093 | clients/google-api-services-testing/v1/1.29.2/com/google/api/services/testing/Testing.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.testing;
/**
* Service definition for Testing (v1).
*
* <p>
* Allows developers to run automated tests for their mobile applications on Google infrastructure.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/cloud-test-lab/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link TestingRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Testing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.29.2 of the Cloud Testing 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://testing.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 Testing(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
*/
Testing(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 ApplicationDetailService collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.ApplicationDetailService.List request = testing.applicationDetailService().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public ApplicationDetailService applicationDetailService() {
return new ApplicationDetailService();
}
/**
* The "applicationDetailService" collection of methods.
*/
public class ApplicationDetailService {
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @return the request
*/
public GetApkDetails getApkDetails(com.google.api.services.testing.model.FileReference content) throws java.io.IOException {
GetApkDetails result = new GetApkDetails(content);
initialize(result);
return result;
}
public class GetApkDetails extends TestingRequest<com.google.api.services.testing.model.GetApkDetailsResponse> {
private static final String REST_PATH = "v1/applicationDetailService/getApkDetails";
/**
* Gets the details of an Android application APK.
*
* Create a request for the method "applicationDetailService.getApkDetails".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. <p>
* {@link GetApkDetails#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR
* equest)} must be called to initialize this instance immediately after invoking the constructor.
* </p>
*
* @param content the {@link com.google.api.services.testing.model.FileReference}
* @since 1.13
*/
protected GetApkDetails(com.google.api.services.testing.model.FileReference content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.GetApkDetailsResponse.class);
}
@Override
public GetApkDetails set$Xgafv(java.lang.String $Xgafv) {
return (GetApkDetails) super.set$Xgafv($Xgafv);
}
@Override
public GetApkDetails setAccessToken(java.lang.String accessToken) {
return (GetApkDetails) super.setAccessToken(accessToken);
}
@Override
public GetApkDetails setAlt(java.lang.String alt) {
return (GetApkDetails) super.setAlt(alt);
}
@Override
public GetApkDetails setCallback(java.lang.String callback) {
return (GetApkDetails) super.setCallback(callback);
}
@Override
public GetApkDetails setFields(java.lang.String fields) {
return (GetApkDetails) super.setFields(fields);
}
@Override
public GetApkDetails setKey(java.lang.String key) {
return (GetApkDetails) super.setKey(key);
}
@Override
public GetApkDetails setOauthToken(java.lang.String oauthToken) {
return (GetApkDetails) super.setOauthToken(oauthToken);
}
@Override
public GetApkDetails setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetApkDetails) super.setPrettyPrint(prettyPrint);
}
@Override
public GetApkDetails setQuotaUser(java.lang.String quotaUser) {
return (GetApkDetails) super.setQuotaUser(quotaUser);
}
@Override
public GetApkDetails setUploadType(java.lang.String uploadType) {
return (GetApkDetails) super.setUploadType(uploadType);
}
@Override
public GetApkDetails setUploadProtocol(java.lang.String uploadProtocol) {
return (GetApkDetails) super.setUploadProtocol(uploadProtocol);
}
@Override
public GetApkDetails set(String parameterName, Object value) {
return (GetApkDetails) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.Projects.List request = testing.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the TestMatrices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestMatrices.List request = testing.testMatrices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestMatrices testMatrices() {
return new TestMatrices();
}
/**
* The "testMatrices" collection of methods.
*/
public class TestMatrices {
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have no
* effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @return the request
*/
public Cancel cancel(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Cancel result = new Cancel(projectId, testMatrixId);
initialize(result);
return result;
}
public class Cancel extends TestingRequest<com.google.api.services.testing.model.CancelTestMatrixResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}:cancel";
/**
* Cancels unfinished test executions in a test matrix. This call returns immediately and
* cancellation proceeds asychronously. If the matrix is already final, this operation will have
* no effect.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.cancel".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link
* Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Cloud project that owns the test.
* @param testMatrixId Test matrix that will be canceled.
* @since 1.13
*/
protected Cancel(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "POST", REST_PATH, null, com.google.api.services.testing.model.CancelTestMatrixResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified.");
}
@Override
public Cancel set$Xgafv(java.lang.String $Xgafv) {
return (Cancel) super.set$Xgafv($Xgafv);
}
@Override
public Cancel setAccessToken(java.lang.String accessToken) {
return (Cancel) super.setAccessToken(accessToken);
}
@Override
public Cancel setAlt(java.lang.String alt) {
return (Cancel) super.setAlt(alt);
}
@Override
public Cancel setCallback(java.lang.String callback) {
return (Cancel) super.setCallback(callback);
}
@Override
public Cancel setFields(java.lang.String fields) {
return (Cancel) super.setFields(fields);
}
@Override
public Cancel setKey(java.lang.String key) {
return (Cancel) super.setKey(key);
}
@Override
public Cancel setOauthToken(java.lang.String oauthToken) {
return (Cancel) super.setOauthToken(oauthToken);
}
@Override
public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Cancel) super.setPrettyPrint(prettyPrint);
}
@Override
public Cancel setQuotaUser(java.lang.String quotaUser) {
return (Cancel) super.setQuotaUser(quotaUser);
}
@Override
public Cancel setUploadType(java.lang.String uploadType) {
return (Cancel) super.setUploadType(uploadType);
}
@Override
public Cancel setUploadProtocol(java.lang.String uploadProtocol) {
return (Cancel) super.setUploadProtocol(uploadProtocol);
}
/** Cloud project that owns the test. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test. */
public Cancel setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Test matrix that will be canceled. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Test matrix that will be canceled.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Test matrix that will be canceled. */
public Cancel setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Cancel set(String parameterName, Object value) {
return (Cancel) super.set(parameterName, value);
}
}
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200 supported
* executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @return the request
*/
public Create create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) throws java.io.IOException {
Create result = new Create(projectId, content);
initialize(result);
return result;
}
public class Create extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices";
/**
* Creates and runs a matrix of tests according to the given specifications. Unsupported
* environments will be returned in the state UNSUPPORTED. Matrices are limited to at most 200
* supported executions.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if
* the request is malformed or if the matrix expands to more than 200
* supported executions
*
* Create a request for the method "testMatrices.create".
*
* This request holds the parameters needed by the the testing server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId The GCE project under which this job will run.
* @param content the {@link com.google.api.services.testing.model.TestMatrix}
* @since 1.13
*/
protected Create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) {
super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** The GCE project under which this job will run. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** The GCE project under which this job will run.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** The GCE project under which this job will run. */
public Create setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
@com.google.api.client.util.Key
private java.lang.String requestId;
/** A string id used to detect duplicated requests. Ids are automatically scoped to a project, so users
should ensure the ID is unique per-project. A UUID is recommended.
Optional, but strongly recommended.
*/
public java.lang.String getRequestId() {
return requestId;
}
/**
* A string id used to detect duplicated requests. Ids are automatically scoped to a
* project, so users should ensure the ID is unique per-project. A UUID is recommended.
*
* Optional, but strongly recommended.
*/
public Create setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException {
Get result = new Get(projectId, testMatrixId);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestMatrix> {
private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}";
/**
* Checks the status of a test matrix.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the
* request is malformed - NOT_FOUND - if the Test Matrix does not exist
*
* Create a request for the method "testMatrices.get".
*
* This request holds the parameters needed by the the testing 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 Cloud project that owns the test matrix.
* @param testMatrixId Unique test matrix id which was assigned by the service.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String testMatrixId) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestMatrix.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId 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);
}
/** Cloud project that owns the test matrix. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Cloud project that owns the test matrix.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Cloud project that owns the test matrix. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Unique test matrix id which was assigned by the service. */
@com.google.api.client.util.Key
private java.lang.String testMatrixId;
/** Unique test matrix id which was assigned by the service.
*/
public java.lang.String getTestMatrixId() {
return testMatrixId;
}
/** Unique test matrix id which was assigned by the service. */
public Get setTestMatrixId(java.lang.String testMatrixId) {
this.testMatrixId = testMatrixId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
}
/**
* An accessor for creating requests from the TestEnvironmentCatalog collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Testing testing = new Testing(...);}
* {@code Testing.TestEnvironmentCatalog.List request = testing.testEnvironmentCatalog().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public TestEnvironmentCatalog testEnvironmentCatalog() {
return new TestEnvironmentCatalog();
}
/**
* The "testEnvironmentCatalog" collection of methods.
*/
public class TestEnvironmentCatalog {
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the testing server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param environmentType Required. The type of environment that should be listed.
* @return the request
*/
public Get get(java.lang.String environmentType) throws java.io.IOException {
Get result = new Get(environmentType);
initialize(result);
return result;
}
public class Get extends TestingRequest<com.google.api.services.testing.model.TestEnvironmentCatalog> {
private static final String REST_PATH = "v1/testEnvironmentCatalog/{environmentType}";
/**
* Gets the catalog of supported test environments.
*
* May return any of the following canonical error codes:
*
* - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type does not
* exist - INTERNAL - if an internal error occurred
*
* Create a request for the method "testEnvironmentCatalog.get".
*
* This request holds the parameters needed by the the testing 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 environmentType Required. The type of environment that should be listed.
* @since 1.13
*/
protected Get(java.lang.String environmentType) {
super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestEnvironmentCatalog.class);
this.environmentType = com.google.api.client.util.Preconditions.checkNotNull(environmentType, "Required parameter environmentType 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. The type of environment that should be listed. */
@com.google.api.client.util.Key
private java.lang.String environmentType;
/** Required. The type of environment that should be listed.
*/
public java.lang.String getEnvironmentType() {
return environmentType;
}
/** Required. The type of environment that should be listed. */
public Get setEnvironmentType(java.lang.String environmentType) {
this.environmentType = environmentType;
return this;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** For authorization, the cloud project requesting the TestEnvironmentCatalog.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** For authorization, the cloud project requesting the TestEnvironmentCatalog. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Testing}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link Testing}. */
@Override
public Testing build() {
return new Testing(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 TestingRequestInitializer}.
*
* @since 1.12
*/
public Builder setTestingRequestInitializer(
TestingRequestInitializer testingRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(testingRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
oracle/coherence | 38,377 | prj/test/unit/coherence-tests/src/test/java/com/tangosol/internal/net/topic/impl/paged/BatchingOperationsQueueTest.java | /*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package com.tangosol.internal.net.topic.impl.paged;
import com.tangosol.net.topic.TopicPublisherException;
import com.tangosol.util.AssertionException;
import com.tangosol.util.Binary;
import com.tangosol.util.LongArray;
import com.tangosol.util.NullImplementation;
import com.tangosol.util.SparseArray;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Deque;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* @author jk 2015.12.17
*/
@SuppressWarnings("rawtypes")
public class BatchingOperationsQueueTest
{
@Test
public void shouldBeActiveOnCreation()
{
BatchingOperationsQueue<?, ?> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
assertThat(queue.isActive(), is(true));
}
@Test
public void shouldReturnFalseFillingFromEmptyQueue()
{
BatchingOperationsQueue<?, ?> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
assertThat(queue.fillCurrentBatch(1), is(false));
}
@Test
public void shouldReturnEmptyBatch()
{
BatchingOperationsQueue<?, ?> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
List listBatch = queue.getCurrentBatchValues();
assertThat(listBatch, is(notNullValue()));
assertThat(listBatch.isEmpty(), is(true));
}
@Test
public void shouldBeCompleteForEmptyQueue()
{
BatchingOperationsQueue<?, ?> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
assertThat(queue.isBatchComplete(), is(true));
}
@Test
public void shouldCloseEmptyQueue()
{
BatchingOperationsQueue<?, ?> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
queue.close();
assertThat(queue.isActive(), is(false));
}
@Test
public void shouldNotBaAbleToAddToClosedQueue()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
queue.close();
assertThrows(IllegalStateException.class, () -> queue.add(new Binary()));
assertThat(queue.getCurrentBatch().isEmpty(), is(true));
assertThat(queue.getPending().isEmpty(), is(true));
assertThat(queue.getTrigger().get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
}
@Test
public void shouldCompleteTriggerAndCallFunctionOnAdd()
{
AtomicInteger intValue = new AtomicInteger(-1);
int cInitial = 100;
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(intValue::set, cInitial);
AtomicInteger futureTrigger = queue.getTrigger();
assertThat(futureTrigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
queue.add(new Binary());
assertThat(futureTrigger.get(), is(BatchingOperationsQueue.TRIGGER_CLOSED));
assertThat(intValue.get(), is(cInitial));
}
@Test
public void shouldAddElementsToPendingListInOrder()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
queue.add(new Binary());
queue.add(new Binary());
queue.add(new Binary());
queue.add(new Binary());
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
assertThat(listPending.size(), is(4));
BatchingOperationsQueue<Binary, Void>.Element element1 = listPending.poll();
BatchingOperationsQueue<Binary, Void>.Element element2 = listPending.poll();
BatchingOperationsQueue<Binary, Void>.Element element3 = listPending.poll();
BatchingOperationsQueue<Binary, Void>.Element element4 = listPending.poll();
assertThat(element1, is(notNullValue()));
assertThat(element1.getValue(), is(new Binary()));
assertThat(element2, is(notNullValue()));
assertThat(element2.getValue(), is(new Binary()));
assertThat(element3, is(notNullValue()));
assertThat(element3.getValue(), is(new Binary()));
assertThat(element4, is(notNullValue()));
assertThat(element4.getValue(), is(new Binary()));
}
@Test
public void shouldReturnUncompletedElementsInBatch()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
element1.getFuture().complete(null);
element3.getFuture().complete(null);
List<Binary> list = queue.getCurrentBatchValues();
assertThat(list, is(notNullValue()));
assertThat(list.size(), is(1));
assertThat(list.get(0), is(element2.getValue()));
}
@Test
public void shouldNotBeCompleteIfBatchContainsUncompleteElements()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
element1.getFuture().complete(null);
element3.getFuture().complete(null);
assertThat(queue.isBatchComplete(), is(false));
}
@Test
public void shouldNotBeCompleteIfBatchContainsAllCompleteElements()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
element1.getFuture().complete(null);
element2.getFuture().complete(null);
element3.getFuture().complete(null);
assertThat(queue.isBatchComplete(), is(true));
}
@Test
public void shouldBeCompleteIfBatchIsEmpty()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
listBatch.clear();
assertThat(queue.isBatchComplete(), is(true));
}
@Test
public void shouldCompleteZeroElementsInCurrentBatch()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
queue.completeElements(0, null, NullImplementation.getLongArray(), TopicPublisherException.createFactory(null), null);
assertThat(element1.isDone(), is(false));
assertThat(element2.isDone(), is(false));
assertThat(element3.isDone(), is(false));
assertThat(element4.isDone(), is(false));
assertThat(listBatch.size(), is(3));
}
@Test
public void shouldCompleteSpecifiedNumberOfElementsInCurrentBatch()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
queue.completeElements(2, null, NullImplementation.getLongArray(), TopicPublisherException.createFactory(null), null);
assertThat(element1.isDone(), is(true));
assertThat(element2.isDone(), is(true));
assertThat(element3.isDone(), is(false));
assertThat(element4.isDone(), is(false));
assertThat(listBatch.size(), is(1));
}
@Test
public void shouldCompleteAllElementsInCurrentBatch()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
listPending.add(element4);
queue.completeElements(3, null, NullImplementation.getLongArray(), TopicPublisherException.createFactory(null), null);
assertThat(element1.isDone(), is(true));
assertThat(element2.isDone(), is(true));
assertThat(element3.isDone(), is(true));
assertThat(element4.isDone(), is(false));
assertThat(listBatch.size(), is(0));
}
@Test
public void shouldCompleteElementsExceptionally()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
LongArray<Throwable> aErrors = new SparseArray<>();
Throwable error1 = new RuntimeException("1");
Throwable error3 = new RuntimeException("2");
listBatch.add(element1);
listBatch.add(element2);
listBatch.add(element3);
aErrors.set(0, error1);
aErrors.set(2, error3);
queue.completeElements(3, aErrors, NullImplementation.getLongArray(), TopicPublisherException.createFactory(null), null);
assertThat(element1.isDone(), is(true));
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.isDone(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(false));
assertThat(element3.isDone(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldFillCurrentBatchWithElements()
{
byte[] ab = new byte[1];
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary(ab));
listPending.add(element1);
listPending.add(element2);
listPending.add(element3);
listPending.add(element4);
queue.fillCurrentBatch(2);
assertThat(listBatch.size(), is(2));
assertThat(listBatch.poll(), is(sameInstance(element1)));
assertThat(listBatch.poll(), is(sameInstance(element2)));
assertThat(listPending.size(), is(2));
assertThat(listPending.poll(), is(sameInstance(element3)));
assertThat(listPending.poll(), is(sameInstance(element4)));
}
@Test
public void shouldFillCurrentBatchWithZeroNewElementsIfAlreadyFilled()
{
byte[] ab = new byte[1];
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary(ab));
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary(ab));
listPending.add(element1);
queue.fillCurrentBatch(1);
listPending.add(element2);
listPending.add(element3);
listPending.add(element4);
queue.fillCurrentBatch(1);
assertThat(listBatch.size(), is(1));
assertThat(listBatch.poll(), is(sameInstance(element1)));
assertThat(listPending.size(), is(3));
assertThat(listPending.poll(), is(sameInstance(element2)));
assertThat(listPending.poll(), is(sameInstance(element3)));
assertThat(listPending.poll(), is(sameInstance(element4)));
}
@Test
public void shouldFillCurrentBatchWithAllPendingElements()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listPending.add(element1);
listPending.add(element2);
listPending.add(element3);
listPending.add(element4);
queue.fillCurrentBatch(5);
assertThat(listBatch.size(), is(4));
assertThat(listBatch.poll(), is(sameInstance(element1)));
assertThat(listBatch.poll(), is(sameInstance(element2)));
assertThat(listBatch.poll(), is(sameInstance(element3)));
assertThat(listBatch.poll(), is(sameInstance(element4)));
assertThat(listPending.size(), is(0));
}
@Test
public void shouldRetryOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
AtomicInteger trigger = queue.getTrigger();
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
queue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.Retry);
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_CLOSED));
assertThat(listBatch.isEmpty(), is(true));
assertThat(listPending.size(), is(4));
assertThat(listPending.poll(), is(sameInstance(element1)));
assertThat(listPending.poll(), is(sameInstance(element2)));
assertThat(listPending.poll(), is(sameInstance(element3)));
assertThat(listPending.poll(), is(sameInstance(element4)));
}
@Test
public void shouldCompleteAllElementsWithoutCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
AtomicInteger trigger = queue.getTrigger();
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.Complete);
verify(spyQueue, never()).close();
assertThat(element1.getFuture().isDone(), is(true));
assertThat(element2.getFuture().isDone(), is(true));
assertThat(element3.getFuture().isDone(), is(true));
assertThat(element4.getFuture().isDone(), is(true));
}
@Test
public void shouldCompleteAllElementsAndCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
AtomicInteger trigger = queue.getTrigger();
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.CompleteAndClose);
verify(spyQueue).close();
assertThat(element1.getFuture().isDone(), is(true));
assertThat(element2.getFuture().isDone(), is(true));
assertThat(element3.getFuture().isDone(), is(true));
assertThat(element4.getFuture().isDone(), is(true));
}
@Test
public void shouldCompleteExceptionallyAllElementsWithoutCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
AtomicInteger trigger = queue.getTrigger();
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.CompleteWithException);
verify(spyQueue, never()).close();
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
assertThat(element4.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldCompleteExceptionallyAllElementsAndCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
AtomicInteger trigger = queue.getTrigger();
assertThat(trigger.get(), is(BatchingOperationsQueue.TRIGGER_OPEN));
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.CompleteWithExceptionAndClose);
verify(spyQueue).close();
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
assertThat(element4.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldCompleteExceptionallyIfOnErrorFunctionReturnsNull()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, null);
verify(spyQueue, never()).close();
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
assertThat(element4.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldCancelAllElementsWithoutCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.Cancel);
verify(spyQueue, never()).close();
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
assertThat(element4.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldCancelAllElementsAndCloseOnError()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
BatchingOperationsQueue<Binary, Void> spyQueue = Mockito.spy(queue);
spyQueue.handleError((bin, err) -> throwable, BatchingOperationsQueue.OnErrorAction.CancelAndClose);
verify(spyQueue).close();
assertThat(element1.getFuture().isCompletedExceptionally(), is(true));
assertThat(element2.getFuture().isCompletedExceptionally(), is(true));
assertThat(element3.getFuture().isCompletedExceptionally(), is(true));
assertThat(element4.getFuture().isCompletedExceptionally(), is(true));
}
@Test
public void shouldCreateElement()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
BatchingOperationsQueue<Binary, Void>.Element element = queue.createElement(new Binary());
assertThat(element.getValue(), is(new Binary()));
assertThat(element.getFuture(), is(notNullValue()));
}
@Test
public void shouldNotCompleteElementOnCreation()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
BatchingOperationsQueue<Binary, Void>.Element element = queue.createElement(new Binary());
assertThat(element.isDone(), is(false));
assertThat(element.getFuture().isDone(), is(false));
}
@Test
public void shouldCompleteElement()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
BatchingOperationsQueue<Binary, Void>.Element element = queue.createElement(new Binary());
element.complete(null, null);
assertThat(element.isDone(), is(true));
assertThat(element.getFuture().isDone(), is(true));
assertThat(element.getFuture().isCancelled(), is(false));
assertThat(element.getFuture().isCompletedExceptionally(), is(false));
}
@Test
public void shouldCompleteElementExceptionally()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
BatchingOperationsQueue<Binary, Void>.Element element = queue.createElement(new Binary());
Throwable throwable = new RuntimeException("No!");
element.completeExceptionally(throwable, TopicPublisherException.createFactory(null));
assertThat(element.isDone(), is(true));
assertThat(element.getFuture().isDone(), is(true));
assertThat(element.getFuture().isCancelled(), is(false));
assertThat(element.getFuture().isCompletedExceptionally(), is(true));
assertThrows(ExecutionException.class, () -> element.getFuture().get(1, TimeUnit.MINUTES));
}
@Test
public void shouldFlushQueue()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
CompletableFuture<Void> future = queue.flush();
assertThat(future.isDone(), is(false));
element1.complete(null, null);
assertThat(future.isDone(), is(false));
element2.complete(null, null);
assertThat(future.isDone(), is(false));
element3.complete(null, null);
assertThat(future.isDone(), is(false));
element4.complete(null, null);
assertThat(future.isDone(), is(true));
assertThat(future.isCancelled(), is(false));
assertThat(future.isCompletedExceptionally(), is(false));
}
@Test
public void shouldFlushQueueWhenFuturesCompleteExceptionally()
{
BatchingOperationsQueue<Binary, Void> queue = new BatchingOperationsQueue<>(FUNCTION_DUMMY, 1);
Queue<BatchingOperationsQueue<Binary, Void>.Element> listBatch = queue.getCurrentBatch();
Deque<BatchingOperationsQueue<Binary, Void>.Element> listPending = queue.getPending();
BatchingOperationsQueue<Binary, Void>.Element element1 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element2 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element3 = queue.createElement(new Binary());
BatchingOperationsQueue<Binary, Void>.Element element4 = queue.createElement(new Binary());
listBatch.add(element1);
listBatch.add(element2);
listPending.add(element3);
listPending.add(element4);
CompletableFuture<Void> future = queue.flush();
assertThat(future.isDone(), is(false));
element1.completeExceptionally(new RuntimeException("No!"), TopicPublisherException.createFactory(null));
assertThat(future.isDone(), is(false));
element2.completeExceptionally(new RuntimeException("No!"), TopicPublisherException.createFactory(null));
assertThat(future.isDone(), is(false));
element3.completeExceptionally(new RuntimeException("No!"), TopicPublisherException.createFactory(null));
assertThat(future.isDone(), is(false));
element4.completeExceptionally(new RuntimeException("No!"), TopicPublisherException.createFactory(null));
assertThat(future.isDone(), is(true));
assertThat(future.isCancelled(), is(false));
assertThat(future.isCompletedExceptionally(), is(false));
}
private static final Consumer<Integer> FUNCTION_DUMMY = (val) -> {};
}
|
apache/ofbiz | 38,136 | applications/product/src/main/java/org/apache/ofbiz/product/store/ProductStoreWorker.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.product.store;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.common.geo.GeoWorker;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.party.contact.ContactMechWorker;
import org.apache.ofbiz.product.config.ProductConfigWrapper;
import org.apache.ofbiz.product.product.ProductWorker;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.apache.ofbiz.webapp.website.WebSiteWorker;
/**
* ProductStoreWorker - Worker class for store related functionality
*/
public final class ProductStoreWorker {
public static final String module = ProductStoreWorker.class.getName();
private static Map<String, String> defaultProductStoreEmailScreenLocation = new HashMap<String, String>();
static {
defaultProductStoreEmailScreenLocation.put("PRDS_ODR_CONFIRM", "component://ecommerce/widget/EmailOrderScreens.xml#OrderConfirmNotice");
defaultProductStoreEmailScreenLocation.put("PRDS_ODR_COMPLETE", "component://ecommerce/widget/EmailOrderScreens.xml#OrderCompleteNotice");
defaultProductStoreEmailScreenLocation.put("PRDS_ODR_BACKORDER", "component://ecommerce/widget/EmailOrderScreens.xml#BackorderNotice");
defaultProductStoreEmailScreenLocation.put("PRDS_ODR_CHANGE", "component://ecommerce/widget/EmailOrderScreens.xml#OrderChangeNotice");
defaultProductStoreEmailScreenLocation.put("PRDS_ODR_PAYRETRY", "component://ecommerce/widget/EmailOrderScreens.xml#PaymentRetryNotice");
defaultProductStoreEmailScreenLocation.put("PRDS_RTN_ACCEPT", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnAccept");
defaultProductStoreEmailScreenLocation.put("PRDS_RTN_COMPLETE", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnComplete");
defaultProductStoreEmailScreenLocation.put("PRDS_RTN_CANCEL", "component://ecommerce/widget/EmailReturnScreens.xml#ReturnCancel");
defaultProductStoreEmailScreenLocation.put("PRDS_GC_PURCHASE", "component://ecommerce/widget/EmailGiftCardScreens.xml#GiftCardPurchase");
defaultProductStoreEmailScreenLocation.put("PRDS_GC_RELOAD", "component://ecommerce/widget/EmailGiftCardScreens.xml#GiftCardReload");
defaultProductStoreEmailScreenLocation.put("PRDS_QUO_CONFIRM", "component://order/widget/ordermgr/QuoteScreens.xml#ViewQuoteSimple");
defaultProductStoreEmailScreenLocation.put("PRDS_PWD_RETRIEVE", "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail");
defaultProductStoreEmailScreenLocation.put("PRDS_TELL_FRIEND", "component://ecommerce/widget/EmailProductScreens.xml#TellFriend");
defaultProductStoreEmailScreenLocation.put("PRDS_CUST_REGISTER", "component://securityext/widget/EmailSecurityScreens.xml#PasswordEmail");
}
private ProductStoreWorker() {}
public static GenericValue getProductStore(String productStoreId, Delegator delegator) {
if (productStoreId == null || delegator == null) {
return null;
}
GenericValue productStore = null;
try {
productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting ProductStore entity", module);
}
return productStore;
}
public static GenericValue getProductStore(ServletRequest request) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productStoreId = ProductStoreWorker.getProductStoreId(request);
return ProductStoreWorker.getProductStore(productStoreId, delegator);
}
public static String getProductStoreId(ServletRequest request) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if (session != null && session.getAttribute("productStoreId") != null) {
return (String) session.getAttribute("productStoreId");
} else {
GenericValue webSite = WebSiteWorker.getWebSite(httpRequest);
if (webSite != null) {
String productStoreId = webSite.getString("productStoreId");
// might be nice to do this, but not needed and has a problem with dependencies: setSessionProductStore(productStoreId, httpRequest);
return productStoreId;
}
}
return null;
}
public static String getStoreCurrencyUomId(HttpServletRequest request) {
GenericValue productStore = getProductStore(request);
if (UtilValidate.isEmpty(productStore)) {
Debug.logError(
"No product store found in request, cannot set CurrencyUomId!", module);
return null;
} else {
return UtilHttp.getCurrencyUom(request.getSession(), productStore.getString("defaultCurrencyUomId"));
}
}
public static Locale getStoreLocale(HttpServletRequest request) {
GenericValue productStore = getProductStore(request);
if (UtilValidate.isEmpty(productStore)) {
Debug.logError(
"No product store found in request, cannot set locale!", module);
return null;
} else {
return UtilHttp.getLocale(request, request.getSession(), productStore.getString("defaultLocaleString"));
}
}
public static TimeZone getStoreTimeZone(HttpServletRequest request) {
GenericValue productStore = getProductStore(request);
if (UtilValidate.isEmpty(productStore)) {
Debug.logError("No product store found in request, cannot set timezone!", module);
return null;
} else {
return UtilHttp.getTimeZone(request, request.getSession(), productStore.getString("defaultTimeZoneString"));
}
}
public static String determineSingleFacilityForStore(Delegator delegator, String productStoreId) {
GenericValue productStore = null;
try {
productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (productStore != null) {
if ("Y".equalsIgnoreCase(productStore.getString("oneInventoryFacility"))) {
return productStore.getString("inventoryFacilityId");
}
}
return null;
}
public static boolean autoSaveCart(Delegator delegator, String productStoreId) {
return autoSaveCart(getProductStore(productStoreId, delegator));
}
public static boolean autoSaveCart(GenericValue productStore) {
return productStore == null ? false : "Y".equalsIgnoreCase(productStore.getString("autoSaveCart"));
}
public static String getProductStorePayToPartyId(String productStoreId, Delegator delegator) {
return getProductStorePayToPartyId(getProductStore(productStoreId, delegator));
}
public static String getProductStorePayToPartyId(GenericValue productStore) {
String payToPartyId = "Company"; // default value
if (productStore != null && productStore.get("payToPartyId") != null) {
payToPartyId = productStore.getString("payToPartyId");
}
return payToPartyId;
}
public static String getProductStorePaymentProperties(ServletRequest request, String paymentMethodTypeId, String paymentServiceTypeEnumId, boolean anyServiceType) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productStoreId = ProductStoreWorker.getProductStoreId(request);
return ProductStoreWorker.getProductStorePaymentProperties(delegator, productStoreId, paymentMethodTypeId, paymentServiceTypeEnumId, anyServiceType);
}
public static String getProductStorePaymentProperties(Delegator delegator, String productStoreId, String paymentMethodTypeId, String paymentServiceTypeEnumId, boolean anyServiceType) {
GenericValue setting = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, paymentMethodTypeId, paymentServiceTypeEnumId, anyServiceType);
String payProps = "payment.properties";
if (setting != null && setting.get("paymentPropertiesPath") != null) {
payProps = setting.getString("paymentPropertiesPath");
}
return payProps;
}
public static GenericValue getProductStorePaymentSetting(Delegator delegator, String productStoreId, String paymentMethodTypeId, String paymentServiceTypeEnumId, boolean anyServiceType) {
GenericValue storePayment = null;
try {
storePayment = EntityQuery.use(delegator).from("ProductStorePaymentSetting").where("productStoreId", productStoreId, "paymentMethodTypeId", paymentMethodTypeId, "paymentServiceTypeEnumId", paymentServiceTypeEnumId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Problems looking up store payment settings", module);
}
if (anyServiceType) {
if (storePayment == null) {
try {
storePayment = EntityQuery.use(delegator).from("ProductStorePaymentSetting").where("productStoreId", productStoreId, "paymentMethodTypeId", paymentMethodTypeId).queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, "Problems looking up store payment settings", module);
}
}
if (storePayment == null) {
try {
storePayment = EntityQuery.use(delegator).from("ProductStorePaymentSetting").where("productStoreId", productStoreId).queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, "Problems looking up store payment settings", module);
}
}
}
return storePayment;
}
public static List<GenericValue> getProductStoreShipmentMethods(Delegator delegator, String productStoreId,
String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId) {
// check for an external service call
List<GenericValue> storeShipMethods = null;
try {
storeShipMethods = EntityQuery.use(delegator).from("ProductStoreShipmentMeth")
.where("productStoreId", productStoreId, "shipmentMethodTypeId", shipmentMethodTypeId,
"partyId", carrierPartyId, "roleTypeId", carrierRoleTypeId)
.cache(true)
.queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return storeShipMethods;
}
public static GenericValue getProductStoreShipmentMethod(Delegator delegator, String productStoreId,
String shipmentMethodTypeId, String carrierPartyId, String carrierRoleTypeId) {
// TODO: selecting the first record is a far from optimal solution but, since the productStoreShipmentMethod
// is currently used to get the service name to get the online estimate, this should not be a huge deal for now.
return EntityUtil.getFirst(getProductStoreShipmentMethods(delegator, productStoreId, shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId));
}
public static List<GenericValue> getAvailableStoreShippingMethods(Delegator delegator, String productStoreId, GenericValue shippingAddress, List<BigDecimal> itemSizes, Map<String, BigDecimal> featureIdMap, BigDecimal weight, BigDecimal orderTotal) {
if (featureIdMap == null) {
featureIdMap = new HashMap<String, BigDecimal>();
}
List<GenericValue> shippingMethods = null;
try {
shippingMethods = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where("productStoreId", productStoreId).orderBy("sequenceNumber").cache(true).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductStore shipping methods", module);
return null;
}
// clone the list for concurrent modification
List<GenericValue> returnShippingMethods = UtilMisc.makeListWritable(shippingMethods);
if (shippingMethods != null) {
for (GenericValue method: shippingMethods) {
// test min/max weight first
BigDecimal minWeight = method.getBigDecimal("minWeight");
BigDecimal maxWeight = method.getBigDecimal("maxWeight");
if (minWeight != null && minWeight.compareTo(BigDecimal.ZERO) > 0 && minWeight.compareTo(weight) > 0) {
returnShippingMethods.remove(method);
continue;
}
if (maxWeight != null && maxWeight.compareTo(BigDecimal.ZERO) > 0 && maxWeight.compareTo(weight) < 0) {
returnShippingMethods.remove(method);
continue;
}
// test order total
BigDecimal minTotal = method.getBigDecimal("minTotal");
BigDecimal maxTotal = method.getBigDecimal("maxTotal");
if (minTotal != null && minTotal.compareTo(BigDecimal.ZERO) > 0 && minTotal.compareTo(orderTotal) > 0) {
returnShippingMethods.remove(method);
continue;
}
if (maxTotal != null && maxTotal.compareTo(BigDecimal.ZERO) > 0 && maxTotal.compareTo(orderTotal) < 0) {
returnShippingMethods.remove(method);
continue;
}
// test product sizes
BigDecimal minSize = method.getBigDecimal("minSize");
BigDecimal maxSize = method.getBigDecimal("maxSize");
if (minSize != null && minSize.compareTo(BigDecimal.ZERO) > 0) {
boolean allMatch = false;
if (itemSizes != null) {
allMatch = true;
for (BigDecimal size: itemSizes) {
if (size.compareTo(minSize) < 0) {
allMatch = false;
}
}
}
if (!allMatch) {
returnShippingMethods.remove(method);
continue;
}
}
if (maxSize != null && maxSize.compareTo(BigDecimal.ZERO) > 0) {
boolean allMatch = false;
if (itemSizes != null) {
allMatch = true;
for (BigDecimal size: itemSizes) {
if (size.compareTo(maxSize) > 0) {
allMatch = false;
}
}
}
if (!allMatch) {
returnShippingMethods.remove(method);
continue;
}
}
// check USPS address
String allowUspsAddr = method.getString("allowUspsAddr");
String requireUspsAddr = method.getString("requireUspsAddr");
boolean isUspsAddress = ContactMechWorker.isUspsAddress(shippingAddress);
if ("N".equals(allowUspsAddr) && isUspsAddress) {
returnShippingMethods.remove(method);
continue;
}
if ("Y".equals(requireUspsAddr) && !isUspsAddress) {
returnShippingMethods.remove(method);
continue;
}
// check company address
String companyPartyId = method.getString("companyPartyId");
String allowCompanyAddr = method.getString("allowCompanyAddr");
String requireCompanyAddr = method.getString("requireCompanyAddr");
boolean isCompanyAddress = ContactMechWorker.isCompanyAddress(shippingAddress, companyPartyId);
if ("N".equals(allowCompanyAddr) && isCompanyAddress) {
returnShippingMethods.remove(method);
continue;
}
if ("Y".equals(requireCompanyAddr) && !isCompanyAddress) {
returnShippingMethods.remove(method);
continue;
}
// check the items excluded from shipping
String includeFreeShipping = method.getString("includeNoChargeItems");
if (includeFreeShipping != null && "N".equalsIgnoreCase(includeFreeShipping)) {
if (UtilValidate.isEmpty(itemSizes) && orderTotal.compareTo(BigDecimal.ZERO) == 0) {
returnShippingMethods.remove(method);
continue;
}
}
// check the geos
String includeGeoId = method.getString("includeGeoId");
String excludeGeoId = method.getString("excludeGeoId");
if (UtilValidate.isNotEmpty(includeGeoId) || UtilValidate.isNotEmpty(excludeGeoId)) {
if (shippingAddress == null) {
returnShippingMethods.remove(method);
continue;
}
}
if (UtilValidate.isNotEmpty(includeGeoId)) {
List<GenericValue> includeGeoGroup = GeoWorker.expandGeoGroup(includeGeoId, delegator);
if (!GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("countryGeoId"), delegator) &&
!GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("stateProvinceGeoId"), delegator) &&
!GeoWorker.containsGeo(includeGeoGroup, shippingAddress.getString("postalCodeGeoId"), delegator)) {
// not in required included geos
returnShippingMethods.remove(method);
continue;
}
}
if (UtilValidate.isNotEmpty(excludeGeoId)) {
List<GenericValue> excludeGeoGroup = GeoWorker.expandGeoGroup(excludeGeoId, delegator);
if (GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("countryGeoId"), delegator) ||
GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("stateProvinceGeoId"), delegator) ||
GeoWorker.containsGeo(excludeGeoGroup, shippingAddress.getString("postalCodeGeoId"), delegator)) {
// in excluded geos
returnShippingMethods.remove(method);
continue;
}
}
// check the features
String includeFeatures = method.getString("includeFeatureGroup");
String excludeFeatures = method.getString("excludeFeatureGroup");
if (UtilValidate.isNotEmpty(includeFeatures)) {
List<GenericValue> includedFeatures = null;
try {
includedFeatures = EntityQuery.use(delegator).from("ProductFeatureGroupAppl").where("productFeatureGroupId", includeFeatures).cache(true).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to lookup ProductFeatureGroupAppl records for group : " + includeFeatures, module);
}
if (includedFeatures != null) {
boolean foundOne = false;
for (GenericValue appl: includedFeatures) {
if (featureIdMap.containsKey(appl.getString("productFeatureId"))) {
foundOne = true;
break;
}
}
if (!foundOne) {
returnShippingMethods.remove(method);
continue;
}
}
}
if (UtilValidate.isNotEmpty(excludeFeatures)) {
List<GenericValue> excludedFeatures = null;
try {
excludedFeatures = EntityQuery.use(delegator).from("ProductFeatureGroupAppl").where("productFeatureGroupId", excludeFeatures).cache(true).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to lookup ProductFeatureGroupAppl records for group : " + excludeFeatures, module);
}
if (excludedFeatures != null) {
for (GenericValue appl: excludedFeatures) {
if (featureIdMap.containsKey(appl.getString("productFeatureId"))) {
returnShippingMethods.remove(method);
continue;
}
}
}
}
}
}
return returnShippingMethods;
}
public static ProductStoreSurveyWrapper getRandomSurveyWrapper(HttpServletRequest request, String groupName) {
GenericValue productStore = getProductStore(request);
HttpSession session = request.getSession();
if (productStore == null) {
return null;
}
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (userLogin == null) {
userLogin = (GenericValue) session.getAttribute("autoUserLogin");
}
String partyId = userLogin != null ? userLogin.getString("partyId") : null;
String origParamMapId = UtilHttp.stashParameterMap(request);
Map<String, Object> passThruFields = UtilMisc.<String, Object>toMap("_ORIG_PARAM_MAP_ID_", origParamMapId);
return getRandomSurveyWrapper(productStore.getDelegator(), productStore.getString("productStoreId"), groupName, partyId, passThruFields);
}
public static ProductStoreSurveyWrapper getRandomSurveyWrapper(Delegator delegator, String productStoreId, String groupName, String partyId, Map<String, Object> passThruFields) {
List<GenericValue> randomSurveys = getSurveys(delegator, productStoreId, groupName, null, "RANDOM_POLL", null);
if (UtilValidate.isNotEmpty(randomSurveys)) {
Random rand = new Random();
int index = rand.nextInt(randomSurveys.size());
GenericValue appl = randomSurveys.get(index);
return new ProductStoreSurveyWrapper(appl, partyId, passThruFields);
} else {
return null;
}
}
public static List<GenericValue> getProductSurveys(Delegator delegator, String productStoreId, String productId, String surveyApplTypeId) {
return getSurveys(delegator, productStoreId, null, productId, surveyApplTypeId, null);
}
public static List<GenericValue> getProductSurveys(Delegator delegator, String productStoreId, String productId, String surveyApplTypeId, String parentProductId) {
return getSurveys(delegator, productStoreId, null, productId, surveyApplTypeId,parentProductId);
}
public static List<GenericValue> getSurveys(Delegator delegator, String productStoreId, String groupName, String productId, String surveyApplTypeId, String parentProductId) {
List<GenericValue> surveys = new LinkedList<GenericValue>();
List<GenericValue> storeSurveys = null;
try {
storeSurveys = EntityQuery.use(delegator).from("ProductStoreSurveyAppl").where("productStoreId", productStoreId, "surveyApplTypeId", surveyApplTypeId).orderBy("sequenceNum").cache(true).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductStoreSurveyAppl for store : " + productStoreId, module);
return surveys;
}
// limit by date
storeSurveys = EntityUtil.filterByDate(storeSurveys);
// limit based on group name
if (UtilValidate.isNotEmpty(groupName)) {
storeSurveys = EntityUtil.filterByAnd(storeSurveys, UtilMisc.toMap("groupName", groupName));
}
Debug.logInfo("getSurvey for product " + productId,module);
// limit by product
if (UtilValidate.isNotEmpty(productId) && UtilValidate.isNotEmpty(storeSurveys)) {
for (GenericValue surveyAppl: storeSurveys) {
GenericValue product = null;
String virtualProductId = null;
// if the item is a variant, get its virtual productId
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
if ((product != null) && ("Y".equals(product.get("isVariant")))) {
if (parentProductId != null) {
virtualProductId = parentProductId;
}
else {
virtualProductId = ProductWorker.getVariantVirtualId(product);
}
Debug.logInfo("getSurvey for virtual product " + virtualProductId,module);
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem finding product from productId " + productId, module);
}
// use survey if productId or virtualProductId of the variant product is in the ProductStoreSurveyAppl
if (surveyAppl.get("productId") != null) {
if (surveyAppl.get("productId").equals(productId)) {
surveys.add(surveyAppl);
} else if ((virtualProductId != null) && (surveyAppl.getString("productId").equals(virtualProductId))) {
surveys.add(surveyAppl);
}
} else if (surveyAppl.get("productCategoryId") != null) {
List<GenericValue> categoryMembers = null;
try {
categoryMembers = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", surveyAppl.get("productCategoryId")).cache(true).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductCategoryMember records for survey application : " + surveyAppl, module);
}
if (categoryMembers != null) {
for (GenericValue member: categoryMembers) {
if (productId != null && productId.equals(member.getString("productId"))) {
surveys.add(surveyAppl);
break;
} else if ((virtualProductId != null) && (virtualProductId.equals(member.getString("productId")))) { // similarly, check if virtual productId is in category
surveys.add(surveyAppl);
break;
}
}
}
}
}
} else if (storeSurveys != null) {
surveys.addAll(storeSurveys);
}
return surveys;
}
/** Returns the number of responses for this survey by party */
public static int checkSurveyResponse(HttpServletRequest request, String surveyId) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String productStoreId = getProductStoreId(request);
if (userLogin == null) {
return -1;
}
return checkSurveyResponse(delegator, userLogin.getString("partyId"), productStoreId, surveyId);
}
/** Returns the number of responses for this survey by party */
public static int checkSurveyResponse(Delegator delegator, String partyId, String productStoreId, String surveyId) {
if (delegator == null || partyId == null || productStoreId == null) {
return -1;
}
List<GenericValue> surveyResponse = null;
try {
surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyId", surveyId, "partyId", partyId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return -1;
}
if (UtilValidate.isEmpty(surveyResponse)) {
return 0;
} else {
return surveyResponse.size();
}
}
public static boolean isStoreInventoryRequired(ServletRequest request, GenericValue product) {
return isStoreInventoryRequiredAndAvailable(request, product, null, Boolean.TRUE, null);
}
public static boolean isStoreInventoryAvailable(ServletRequest request, GenericValue product, BigDecimal quantity) {
return isStoreInventoryRequiredAndAvailable(request, product, quantity, null, Boolean.TRUE);
}
/**
* This method is used in the showcart pages to determine whether or not to show the inventory message and
* in the productdetail pages to determine whether or not to show the item as out of stock.
*
* @param request ServletRequest (or HttpServletRequest of course)
* @param product GenericValue representing the product in question
* @param quantity Quantity desired.
* @param wantRequired If true then inventory required must be true for the result to be true, if false must be false; if null don't care
* @param wantAvailable If true then inventory avilable must be true for the result to be true, if false must be false; if null don't care
*/
public static boolean isStoreInventoryRequiredAndAvailable(ServletRequest request, GenericValue product, BigDecimal quantity, Boolean wantRequired, Boolean wantAvailable) {
GenericValue productStore = getProductStore(request);
if (productStore == null) {
Debug.logWarning("No ProductStore found, return false for inventory check", module);
return false;
}
if (product == null) {
Debug.logWarning("No Product passed, return false for inventory check", module);
return false;
}
if (quantity == null) quantity = BigDecimal.ONE;
String productStoreId = productStore.getString("productStoreId");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
try {
Boolean requiredOkay = null;
if (wantRequired != null) {
Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryRequired", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore));
if (ServiceUtil.isError(invReqResult)) {
Debug.logError("Error calling isStoreInventoryRequired service, result is: " + invReqResult, module);
return false;
}
requiredOkay = Boolean.valueOf(wantRequired.booleanValue() == "Y".equals(invReqResult.get("requireInventory")));
}
Boolean availableOkay = null;
if (wantAvailable != null) {
Map<String, Object> invAvailResult = dispatcher.runSync("isStoreInventoryAvailable", UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"), "product", product, "productStore", productStore, "quantity", quantity));
if (ServiceUtil.isError(invAvailResult)) {
Debug.logError("Error calling isStoreInventoryAvailable service, result is: " + invAvailResult, module);
return false;
}
availableOkay = Boolean.valueOf(wantAvailable.booleanValue() == "Y".equals(invAvailResult.get("available")));
}
if ((requiredOkay == null || requiredOkay.booleanValue()) && (availableOkay == null || availableOkay.booleanValue())) {
return true;
} else {
return false;
}
} catch (GenericServiceException e) {
String errMsg = "Fatal error calling inventory checking services: " + e.toString();
Debug.logError(e, errMsg, module);
return false;
}
}
public static boolean isStoreInventoryAvailable(ServletRequest request, ProductConfigWrapper productConfig, BigDecimal quantity) {
GenericValue productStore = getProductStore(request);
if (productStore == null) {
Debug.logWarning("No ProductStore found, return false for inventory check", module);
return false;
}
String productStoreId = productStore.getString("productStoreId");
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
return isStoreInventoryAvailable(productStoreId, productConfig, quantity, delegator, dispatcher);
}
/** check inventory availability for the given catalog, product, quantity, etc */
public static boolean isStoreInventoryAvailable(String productStoreId, ProductConfigWrapper productConfig, BigDecimal quantity, Delegator delegator, LocalDispatcher dispatcher) {
GenericValue productStore = getProductStore(productStoreId, delegator);
if (productStore == null) {
Debug.logWarning("No ProductStore found with id " + productStoreId + ", returning false for inventory available check", module);
return false;
}
// if prodCatalog is set to not check inventory break here
if ("N".equals(productStore.getString("checkInventory"))) {
// note: if not set, defaults to yes, check inventory
if (Debug.verboseOn()) Debug.logVerbose("ProductStore with id " + productStoreId + ", is set to NOT check inventory, returning true for inventory available check", module);
return true;
}
boolean isInventoryAvailable = false;
if ("Y".equals(productStore.getString("oneInventoryFacility"))) {
String inventoryFacilityId = productStore.getString("inventoryFacilityId");
if (UtilValidate.isEmpty(inventoryFacilityId)) {
Debug.logWarning("ProductStore with id " + productStoreId + " has Y for oneInventoryFacility but inventoryFacilityId is empty, returning false for inventory check", module);
return false;
}
return ProductWorker.isProductInventoryAvailableByFacility(productConfig, inventoryFacilityId, quantity, dispatcher);
} else {
GenericValue product = productConfig.getProduct();
List<GenericValue> productFacilities = null;
try {
productFacilities = product.getRelated("ProductFacility", null, null, true);
} catch (GenericEntityException e) {
Debug.logWarning(e, "Error invoking getRelated in isCatalogInventoryAvailable", module);
return false;
}
if (UtilValidate.isNotEmpty(productFacilities)) {
for (GenericValue pfValue: productFacilities) {
isInventoryAvailable = ProductWorker.isProductInventoryAvailableByFacility(productConfig, pfValue.getString("facilityId"), quantity, dispatcher);
if (isInventoryAvailable == true) {
return isInventoryAvailable;
}
}
}
return false;
}
}
public static String getDefaultProductStoreEmailScreenLocation(String emailType) {
return defaultProductStoreEmailScreenLocation.get(emailType);
}
}
|
googleapis/google-cloud-java | 37,814 | java-networkconnectivity/proto-google-cloud-networkconnectivity-v1/src/main/java/com/google/cloud/networkconnectivity/v1/ListSpokesRequest.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/networkconnectivity/v1/hub.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.networkconnectivity.v1;
/**
*
*
* <pre>
* The request for
* [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes].
* </pre>
*
* Protobuf type {@code google.cloud.networkconnectivity.v1.ListSpokesRequest}
*/
public final class ListSpokesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.networkconnectivity.v1.ListSpokesRequest)
ListSpokesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSpokesRequest.newBuilder() to construct.
private ListSpokesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSpokesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSpokesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkconnectivity.v1.HubProto
.internal_static_google_cloud_networkconnectivity_v1_ListSpokesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkconnectivity.v1.HubProto
.internal_static_google_cloud_networkconnectivity_v1_ListSpokesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkconnectivity.v1.ListSpokesRequest.class,
com.google.cloud.networkconnectivity.v1.ListSpokesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource.
* </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.
* </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 per page.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.networkconnectivity.v1.ListSpokesRequest)) {
return super.equals(obj);
}
com.google.cloud.networkconnectivity.v1.ListSpokesRequest other =
(com.google.cloud.networkconnectivity.v1.ListSpokesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest 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.networkconnectivity.v1.ListSpokesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest 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.networkconnectivity.v1.ListSpokesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest 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.networkconnectivity.v1.ListSpokesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest 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.networkconnectivity.v1.ListSpokesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest 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.networkconnectivity.v1.ListSpokesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request for
* [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes].
* </pre>
*
* Protobuf type {@code google.cloud.networkconnectivity.v1.ListSpokesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.networkconnectivity.v1.ListSpokesRequest)
com.google.cloud.networkconnectivity.v1.ListSpokesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkconnectivity.v1.HubProto
.internal_static_google_cloud_networkconnectivity_v1_ListSpokesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkconnectivity.v1.HubProto
.internal_static_google_cloud_networkconnectivity_v1_ListSpokesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkconnectivity.v1.ListSpokesRequest.class,
com.google.cloud.networkconnectivity.v1.ListSpokesRequest.Builder.class);
}
// Construct using com.google.cloud.networkconnectivity.v1.ListSpokesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.networkconnectivity.v1.HubProto
.internal_static_google_cloud_networkconnectivity_v1_ListSpokesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.networkconnectivity.v1.ListSpokesRequest getDefaultInstanceForType() {
return com.google.cloud.networkconnectivity.v1.ListSpokesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.networkconnectivity.v1.ListSpokesRequest build() {
com.google.cloud.networkconnectivity.v1.ListSpokesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.networkconnectivity.v1.ListSpokesRequest buildPartial() {
com.google.cloud.networkconnectivity.v1.ListSpokesRequest result =
new com.google.cloud.networkconnectivity.v1.ListSpokesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.networkconnectivity.v1.ListSpokesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.networkconnectivity.v1.ListSpokesRequest) {
return mergeFrom((com.google.cloud.networkconnectivity.v1.ListSpokesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.networkconnectivity.v1.ListSpokesRequest other) {
if (other == com.google.cloud.networkconnectivity.v1.ListSpokesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource.
* </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.
* </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.
* </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.
* </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.
* </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 per page.
* </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 per page.
* </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 per page.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression that filters the list of results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Sort the results by a certain order.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.networkconnectivity.v1.ListSpokesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.networkconnectivity.v1.ListSpokesRequest)
private static final com.google.cloud.networkconnectivity.v1.ListSpokesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.networkconnectivity.v1.ListSpokesRequest();
}
public static com.google.cloud.networkconnectivity.v1.ListSpokesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSpokesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListSpokesRequest>() {
@java.lang.Override
public ListSpokesRequest 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<ListSpokesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSpokesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.networkconnectivity.v1.ListSpokesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,843 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListProcessesRequest.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/lva_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Message for requesting list of Processes.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListProcessesRequest}
*/
public final class ListProcessesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListProcessesRequest)
ListProcessesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProcessesRequest.newBuilder() to construct.
private ListProcessesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProcessesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProcessesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListProcessesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListProcessesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListProcessesRequest.class,
com.google.cloud.visionai.v1.ListProcessesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.ListProcessesRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ListProcessesRequest other =
(com.google.cloud.visionai.v1.ListProcessesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.ListProcessesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListProcessesRequest 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.ListProcessesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListProcessesRequest 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.ListProcessesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListProcessesRequest 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.ListProcessesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListProcessesRequest 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.ListProcessesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListProcessesRequest 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.ListProcessesRequest 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.ListProcessesRequest 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.ListProcessesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Processes.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListProcessesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListProcessesRequest)
com.google.cloud.visionai.v1.ListProcessesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListProcessesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListProcessesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListProcessesRequest.class,
com.google.cloud.visionai.v1.ListProcessesRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ListProcessesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListProcessesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListProcessesRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ListProcessesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListProcessesRequest build() {
com.google.cloud.visionai.v1.ListProcessesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListProcessesRequest buildPartial() {
com.google.cloud.visionai.v1.ListProcessesRequest result =
new com.google.cloud.visionai.v1.ListProcessesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.ListProcessesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.ListProcessesRequest) {
return mergeFrom((com.google.cloud.visionai.v1.ListProcessesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ListProcessesRequest other) {
if (other == com.google.cloud.visionai.v1.ListProcessesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListProcessesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListProcessesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListProcessesRequest)
private static final com.google.cloud.visionai.v1.ListProcessesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListProcessesRequest();
}
public static com.google.cloud.visionai.v1.ListProcessesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProcessesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListProcessesRequest>() {
@java.lang.Override
public ListProcessesRequest 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<ListProcessesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProcessesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListProcessesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,979 | java-vision/proto-google-cloud-vision-v1p3beta1/src/main/java/com/google/cloud/vision/v1p3beta1/CreateProductSetRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p3beta1/product_search_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vision.v1p3beta1;
/**
*
*
* <pre>
* Request message for the `CreateProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p3beta1.CreateProductSetRequest}
*/
public final class CreateProductSetRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p3beta1.CreateProductSetRequest)
CreateProductSetRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateProductSetRequest.newBuilder() to construct.
private CreateProductSetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateProductSetRequest() {
parent_ = "";
productSetId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateProductSetRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_CreateProductSetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.class,
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PRODUCT_SET_FIELD_NUMBER = 2;
private com.google.cloud.vision.v1p3beta1.ProductSet productSet_;
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the productSet field is set.
*/
@java.lang.Override
public boolean hasProductSet() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The productSet.
*/
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ProductSet getProductSet() {
return productSet_ == null
? com.google.cloud.vision.v1p3beta1.ProductSet.getDefaultInstance()
: productSet_;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ProductSetOrBuilder getProductSetOrBuilder() {
return productSet_ == null
? com.google.cloud.vision.v1p3beta1.ProductSet.getDefaultInstance()
: productSet_;
}
public static final int PRODUCT_SET_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object productSetId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The productSetId.
*/
@java.lang.Override
public java.lang.String getProductSetId() {
java.lang.Object ref = productSetId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productSetId_ = s;
return s;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The bytes for productSetId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProductSetIdBytes() {
java.lang.Object ref = productSetId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productSetId_ = 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, getProductSet());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, productSetId_);
}
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, getProductSet());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, productSetId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1p3beta1.CreateProductSetRequest)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest other =
(com.google.cloud.vision.v1p3beta1.CreateProductSetRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasProductSet() != other.hasProductSet()) return false;
if (hasProductSet()) {
if (!getProductSet().equals(other.getProductSet())) return false;
}
if (!getProductSetId().equals(other.getProductSetId())) 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 (hasProductSet()) {
hash = (37 * hash) + PRODUCT_SET_FIELD_NUMBER;
hash = (53 * hash) + getProductSet().hashCode();
}
hash = (37 * hash) + PRODUCT_SET_ID_FIELD_NUMBER;
hash = (53 * hash) + getProductSetId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest 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 `CreateProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p3beta1.CreateProductSetRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p3beta1.CreateProductSetRequest)
com.google.cloud.vision.v1p3beta1.CreateProductSetRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_CreateProductSetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.class,
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.Builder.class);
}
// Construct using com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getProductSetFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
productSet_ = null;
if (productSetBuilder_ != null) {
productSetBuilder_.dispose();
productSetBuilder_ = null;
}
productSetId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.CreateProductSetRequest getDefaultInstanceForType() {
return com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.CreateProductSetRequest build() {
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.CreateProductSetRequest buildPartial() {
com.google.cloud.vision.v1p3beta1.CreateProductSetRequest result =
new com.google.cloud.vision.v1p3beta1.CreateProductSetRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.vision.v1p3beta1.CreateProductSetRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.productSet_ = productSetBuilder_ == null ? productSet_ : productSetBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.productSetId_ = productSetId_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1p3beta1.CreateProductSetRequest) {
return mergeFrom((com.google.cloud.vision.v1p3beta1.CreateProductSetRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p3beta1.CreateProductSetRequest other) {
if (other == com.google.cloud.vision.v1p3beta1.CreateProductSetRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasProductSet()) {
mergeProductSet(other.getProductSet());
}
if (!other.getProductSetId().isEmpty()) {
productSetId_ = other.productSetId_;
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(getProductSetFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
productSetId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.vision.v1p3beta1.ProductSet productSet_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.ProductSet,
com.google.cloud.vision.v1p3beta1.ProductSet.Builder,
com.google.cloud.vision.v1p3beta1.ProductSetOrBuilder>
productSetBuilder_;
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the productSet field is set.
*/
public boolean hasProductSet() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The productSet.
*/
public com.google.cloud.vision.v1p3beta1.ProductSet getProductSet() {
if (productSetBuilder_ == null) {
return productSet_ == null
? com.google.cloud.vision.v1p3beta1.ProductSet.getDefaultInstance()
: productSet_;
} else {
return productSetBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProductSet(com.google.cloud.vision.v1p3beta1.ProductSet value) {
if (productSetBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
productSet_ = value;
} else {
productSetBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProductSet(
com.google.cloud.vision.v1p3beta1.ProductSet.Builder builderForValue) {
if (productSetBuilder_ == null) {
productSet_ = builderForValue.build();
} else {
productSetBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeProductSet(com.google.cloud.vision.v1p3beta1.ProductSet value) {
if (productSetBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& productSet_ != null
&& productSet_ != com.google.cloud.vision.v1p3beta1.ProductSet.getDefaultInstance()) {
getProductSetBuilder().mergeFrom(value);
} else {
productSet_ = value;
}
} else {
productSetBuilder_.mergeFrom(value);
}
if (productSet_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearProductSet() {
bitField0_ = (bitField0_ & ~0x00000002);
productSet_ = null;
if (productSetBuilder_ != null) {
productSetBuilder_.dispose();
productSetBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1p3beta1.ProductSet.Builder getProductSetBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getProductSetFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1p3beta1.ProductSetOrBuilder getProductSetOrBuilder() {
if (productSetBuilder_ != null) {
return productSetBuilder_.getMessageOrBuilder();
} else {
return productSet_ == null
? com.google.cloud.vision.v1p3beta1.ProductSet.getDefaultInstance()
: productSet_;
}
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p3beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.ProductSet,
com.google.cloud.vision.v1p3beta1.ProductSet.Builder,
com.google.cloud.vision.v1p3beta1.ProductSetOrBuilder>
getProductSetFieldBuilder() {
if (productSetBuilder_ == null) {
productSetBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.ProductSet,
com.google.cloud.vision.v1p3beta1.ProductSet.Builder,
com.google.cloud.vision.v1p3beta1.ProductSetOrBuilder>(
getProductSet(), getParentForChildren(), isClean());
productSet_ = null;
}
return productSetBuilder_;
}
private java.lang.Object productSetId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The productSetId.
*/
public java.lang.String getProductSetId() {
java.lang.Object ref = productSetId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productSetId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The bytes for productSetId.
*/
public com.google.protobuf.ByteString getProductSetIdBytes() {
java.lang.Object ref = productSetId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productSetId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @param value The productSetId to set.
* @return This builder for chaining.
*/
public Builder setProductSetId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
productSetId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearProductSetId() {
productSetId_ = getDefaultInstance().getProductSetId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @param value The bytes for productSetId to set.
* @return This builder for chaining.
*/
public Builder setProductSetIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
productSetId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p3beta1.CreateProductSetRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CreateProductSetRequest)
private static final com.google.cloud.vision.v1p3beta1.CreateProductSetRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p3beta1.CreateProductSetRequest();
}
public static com.google.cloud.vision.v1p3beta1.CreateProductSetRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateProductSetRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateProductSetRequest>() {
@java.lang.Override
public CreateProductSetRequest 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<CreateProductSetRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateProductSetRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.CreateProductSetRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,979 | java-vision/proto-google-cloud-vision-v1p4beta1/src/main/java/com/google/cloud/vision/v1p4beta1/CreateProductSetRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p4beta1/product_search_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vision.v1p4beta1;
/**
*
*
* <pre>
* Request message for the `CreateProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.CreateProductSetRequest}
*/
public final class CreateProductSetRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.CreateProductSetRequest)
CreateProductSetRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateProductSetRequest.newBuilder() to construct.
private CreateProductSetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateProductSetRequest() {
parent_ = "";
productSetId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateProductSetRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_CreateProductSetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.class,
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PRODUCT_SET_FIELD_NUMBER = 2;
private com.google.cloud.vision.v1p4beta1.ProductSet productSet_;
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the productSet field is set.
*/
@java.lang.Override
public boolean hasProductSet() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The productSet.
*/
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ProductSet getProductSet() {
return productSet_ == null
? com.google.cloud.vision.v1p4beta1.ProductSet.getDefaultInstance()
: productSet_;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ProductSetOrBuilder getProductSetOrBuilder() {
return productSet_ == null
? com.google.cloud.vision.v1p4beta1.ProductSet.getDefaultInstance()
: productSet_;
}
public static final int PRODUCT_SET_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object productSetId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The productSetId.
*/
@java.lang.Override
public java.lang.String getProductSetId() {
java.lang.Object ref = productSetId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productSetId_ = s;
return s;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The bytes for productSetId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProductSetIdBytes() {
java.lang.Object ref = productSetId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productSetId_ = 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, getProductSet());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, productSetId_);
}
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, getProductSet());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productSetId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, productSetId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1p4beta1.CreateProductSetRequest)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest other =
(com.google.cloud.vision.v1p4beta1.CreateProductSetRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasProductSet() != other.hasProductSet()) return false;
if (hasProductSet()) {
if (!getProductSet().equals(other.getProductSet())) return false;
}
if (!getProductSetId().equals(other.getProductSetId())) 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 (hasProductSet()) {
hash = (37 * hash) + PRODUCT_SET_FIELD_NUMBER;
hash = (53 * hash) + getProductSet().hashCode();
}
hash = (37 * hash) + PRODUCT_SET_ID_FIELD_NUMBER;
hash = (53 * hash) + getProductSetId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest 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 `CreateProductSet` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.CreateProductSetRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.CreateProductSetRequest)
com.google.cloud.vision.v1p4beta1.CreateProductSetRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_CreateProductSetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.class,
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.Builder.class);
}
// Construct using com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getProductSetFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
productSet_ = null;
if (productSetBuilder_ != null) {
productSetBuilder_.dispose();
productSetBuilder_ = null;
}
productSetId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_CreateProductSetRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.CreateProductSetRequest getDefaultInstanceForType() {
return com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.CreateProductSetRequest build() {
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.CreateProductSetRequest buildPartial() {
com.google.cloud.vision.v1p4beta1.CreateProductSetRequest result =
new com.google.cloud.vision.v1p4beta1.CreateProductSetRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.vision.v1p4beta1.CreateProductSetRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.productSet_ = productSetBuilder_ == null ? productSet_ : productSetBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.productSetId_ = productSetId_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1p4beta1.CreateProductSetRequest) {
return mergeFrom((com.google.cloud.vision.v1p4beta1.CreateProductSetRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p4beta1.CreateProductSetRequest other) {
if (other == com.google.cloud.vision.v1p4beta1.CreateProductSetRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasProductSet()) {
mergeProductSet(other.getProductSet());
}
if (!other.getProductSetId().isEmpty()) {
productSetId_ = other.productSetId_;
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(getProductSetFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
productSetId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the ProductSet should be created.
*
* Format is `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.vision.v1p4beta1.ProductSet productSet_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.ProductSet,
com.google.cloud.vision.v1p4beta1.ProductSet.Builder,
com.google.cloud.vision.v1p4beta1.ProductSetOrBuilder>
productSetBuilder_;
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the productSet field is set.
*/
public boolean hasProductSet() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The productSet.
*/
public com.google.cloud.vision.v1p4beta1.ProductSet getProductSet() {
if (productSetBuilder_ == null) {
return productSet_ == null
? com.google.cloud.vision.v1p4beta1.ProductSet.getDefaultInstance()
: productSet_;
} else {
return productSetBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProductSet(com.google.cloud.vision.v1p4beta1.ProductSet value) {
if (productSetBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
productSet_ = value;
} else {
productSetBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProductSet(
com.google.cloud.vision.v1p4beta1.ProductSet.Builder builderForValue) {
if (productSetBuilder_ == null) {
productSet_ = builderForValue.build();
} else {
productSetBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeProductSet(com.google.cloud.vision.v1p4beta1.ProductSet value) {
if (productSetBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& productSet_ != null
&& productSet_ != com.google.cloud.vision.v1p4beta1.ProductSet.getDefaultInstance()) {
getProductSetBuilder().mergeFrom(value);
} else {
productSet_ = value;
}
} else {
productSetBuilder_.mergeFrom(value);
}
if (productSet_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearProductSet() {
bitField0_ = (bitField0_ & ~0x00000002);
productSet_ = null;
if (productSetBuilder_ != null) {
productSetBuilder_.dispose();
productSetBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1p4beta1.ProductSet.Builder getProductSetBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getProductSetFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1p4beta1.ProductSetOrBuilder getProductSetOrBuilder() {
if (productSetBuilder_ != null) {
return productSetBuilder_.getMessageOrBuilder();
} else {
return productSet_ == null
? com.google.cloud.vision.v1p4beta1.ProductSet.getDefaultInstance()
: productSet_;
}
}
/**
*
*
* <pre>
* Required. The ProductSet to create.
* </pre>
*
* <code>
* .google.cloud.vision.v1p4beta1.ProductSet product_set = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.ProductSet,
com.google.cloud.vision.v1p4beta1.ProductSet.Builder,
com.google.cloud.vision.v1p4beta1.ProductSetOrBuilder>
getProductSetFieldBuilder() {
if (productSetBuilder_ == null) {
productSetBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.ProductSet,
com.google.cloud.vision.v1p4beta1.ProductSet.Builder,
com.google.cloud.vision.v1p4beta1.ProductSetOrBuilder>(
getProductSet(), getParentForChildren(), isClean());
productSet_ = null;
}
return productSetBuilder_;
}
private java.lang.Object productSetId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The productSetId.
*/
public java.lang.String getProductSetId() {
java.lang.Object ref = productSetId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productSetId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return The bytes for productSetId.
*/
public com.google.protobuf.ByteString getProductSetIdBytes() {
java.lang.Object ref = productSetId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productSetId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @param value The productSetId to set.
* @return This builder for chaining.
*/
public Builder setProductSetId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
productSetId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearProductSetId() {
productSetId_ = getDefaultInstance().getProductSetId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this ProductSet. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_set_id = 3;</code>
*
* @param value The bytes for productSetId to set.
* @return This builder for chaining.
*/
public Builder setProductSetIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
productSetId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p4beta1.CreateProductSetRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CreateProductSetRequest)
private static final com.google.cloud.vision.v1p4beta1.CreateProductSetRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p4beta1.CreateProductSetRequest();
}
public static com.google.cloud.vision.v1p4beta1.CreateProductSetRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateProductSetRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateProductSetRequest>() {
@java.lang.Override
public CreateProductSetRequest 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<CreateProductSetRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateProductSetRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.CreateProductSetRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,982 | java-discoveryengine/proto-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/ListSchemasResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1beta/schema_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1beta;
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.ListSchemasResponse}
*/
public final class ListSchemasResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1beta.ListSchemasResponse)
ListSchemasResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSchemasResponse.newBuilder() to construct.
private ListSchemasResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSchemasResponse() {
schemas_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSchemasResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.Builder.class);
}
public static final int SCHEMAS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.discoveryengine.v1beta.Schema> schemas_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.discoveryengine.v1beta.Schema> getSchemasList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder>
getSchemasOrBuilderList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
@java.lang.Override
public int getSchemasCount() {
return schemas_.size();
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.Schema getSchemas(int index) {
return schemas_.get(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder getSchemasOrBuilder(int index) {
return schemas_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < schemas_.size(); i++) {
output.writeMessage(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < schemas_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1beta.ListSchemasResponse)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse other =
(com.google.cloud.discoveryengine.v1beta.ListSchemasResponse) obj;
if (!getSchemasList().equals(other.getSchemasList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getSchemasCount() > 0) {
hash = (37 * hash) + SCHEMAS_FIELD_NUMBER;
hash = (53 * hash) + getSchemasList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.ListSchemasResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1beta.ListSchemasResponse)
com.google.cloud.discoveryengine.v1beta.ListSchemasResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
} else {
schemas_ = null;
schemasBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1beta.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListSchemasResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListSchemasResponse getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListSchemasResponse build() {
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListSchemasResponse buildPartial() {
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse result =
new com.google.cloud.discoveryengine.v1beta.ListSchemasResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.discoveryengine.v1beta.ListSchemasResponse result) {
if (schemasBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
schemas_ = java.util.Collections.unmodifiableList(schemas_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.schemas_ = schemas_;
} else {
result.schemas_ = schemasBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.discoveryengine.v1beta.ListSchemasResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1beta.ListSchemasResponse) {
return mergeFrom((com.google.cloud.discoveryengine.v1beta.ListSchemasResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.discoveryengine.v1beta.ListSchemasResponse other) {
if (other == com.google.cloud.discoveryengine.v1beta.ListSchemasResponse.getDefaultInstance())
return this;
if (schemasBuilder_ == null) {
if (!other.schemas_.isEmpty()) {
if (schemas_.isEmpty()) {
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSchemasIsMutable();
schemas_.addAll(other.schemas_);
}
onChanged();
}
} else {
if (!other.schemas_.isEmpty()) {
if (schemasBuilder_.isEmpty()) {
schemasBuilder_.dispose();
schemasBuilder_ = null;
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
schemasBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSchemasFieldBuilder()
: null;
} else {
schemasBuilder_.addAllMessages(other.schemas_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.discoveryengine.v1beta.Schema m =
input.readMessage(
com.google.cloud.discoveryengine.v1beta.Schema.parser(), extensionRegistry);
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(m);
} else {
schemasBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.discoveryengine.v1beta.Schema> schemas_ =
java.util.Collections.emptyList();
private void ensureSchemasIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
schemas_ =
new java.util.ArrayList<com.google.cloud.discoveryengine.v1beta.Schema>(schemas_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1beta.Schema,
com.google.cloud.discoveryengine.v1beta.Schema.Builder,
com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder>
schemasBuilder_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1beta.Schema> getSchemasList() {
if (schemasBuilder_ == null) {
return java.util.Collections.unmodifiableList(schemas_);
} else {
return schemasBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public int getSchemasCount() {
if (schemasBuilder_ == null) {
return schemas_.size();
} else {
return schemasBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1beta.Schema getSchemas(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder setSchemas(int index, com.google.cloud.discoveryengine.v1beta.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.set(index, value);
onChanged();
} else {
schemasBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder setSchemas(
int index, com.google.cloud.discoveryengine.v1beta.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.set(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder addSchemas(com.google.cloud.discoveryengine.v1beta.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(value);
onChanged();
} else {
schemasBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder addSchemas(int index, com.google.cloud.discoveryengine.v1beta.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(index, value);
onChanged();
} else {
schemasBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder addSchemas(
com.google.cloud.discoveryengine.v1beta.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder addSchemas(
int index, com.google.cloud.discoveryengine.v1beta.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder addAllSchemas(
java.lang.Iterable<? extends com.google.cloud.discoveryengine.v1beta.Schema> values) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, schemas_);
onChanged();
} else {
schemasBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder clearSchemas() {
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
schemasBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public Builder removeSchemas(int index) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.remove(index);
onChanged();
} else {
schemasBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1beta.Schema.Builder getSchemasBuilder(int index) {
return getSchemasFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder getSchemasOrBuilder(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public java.util.List<? extends com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder>
getSchemasOrBuilderList() {
if (schemasBuilder_ != null) {
return schemasBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(schemas_);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1beta.Schema.Builder addSchemasBuilder() {
return getSchemasFieldBuilder()
.addBuilder(com.google.cloud.discoveryengine.v1beta.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1beta.Schema.Builder addSchemasBuilder(int index) {
return getSchemasFieldBuilder()
.addBuilder(index, com.google.cloud.discoveryengine.v1beta.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1beta.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1beta.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1beta.Schema.Builder>
getSchemasBuilderList() {
return getSchemasFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1beta.Schema,
com.google.cloud.discoveryengine.v1beta.Schema.Builder,
com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder>
getSchemasFieldBuilder() {
if (schemasBuilder_ == null) {
schemasBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1beta.Schema,
com.google.cloud.discoveryengine.v1beta.Schema.Builder,
com.google.cloud.discoveryengine.v1beta.SchemaOrBuilder>(
schemas_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
schemas_ = null;
}
return schemasBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1beta.ListSchemasResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1beta.ListSchemasResponse)
private static final com.google.cloud.discoveryengine.v1beta.ListSchemasResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1beta.ListSchemasResponse();
}
public static com.google.cloud.discoveryengine.v1beta.ListSchemasResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSchemasResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSchemasResponse>() {
@java.lang.Override
public ListSchemasResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListSchemasResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSchemasResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListSchemasResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,844 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListInstancesRequest.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/platform.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Message for requesting list of Instances.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListInstancesRequest}
*/
public final class ListInstancesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListInstancesRequest)
ListInstancesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListInstancesRequest.newBuilder() to construct.
private ListInstancesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListInstancesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListInstancesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListInstancesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListInstancesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListInstancesRequest.class,
com.google.cloud.visionai.v1.ListInstancesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.ListInstancesRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ListInstancesRequest other =
(com.google.cloud.visionai.v1.ListInstancesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.ListInstancesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListInstancesRequest 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.ListInstancesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListInstancesRequest 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.ListInstancesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListInstancesRequest 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.ListInstancesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListInstancesRequest 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.ListInstancesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListInstancesRequest 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.ListInstancesRequest 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.ListInstancesRequest 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.ListInstancesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Instances.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListInstancesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListInstancesRequest)
com.google.cloud.visionai.v1.ListInstancesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListInstancesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListInstancesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListInstancesRequest.class,
com.google.cloud.visionai.v1.ListInstancesRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ListInstancesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListInstancesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListInstancesRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ListInstancesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListInstancesRequest build() {
com.google.cloud.visionai.v1.ListInstancesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListInstancesRequest buildPartial() {
com.google.cloud.visionai.v1.ListInstancesRequest result =
new com.google.cloud.visionai.v1.ListInstancesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.ListInstancesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.ListInstancesRequest) {
return mergeFrom((com.google.cloud.visionai.v1.ListInstancesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ListInstancesRequest other) {
if (other == com.google.cloud.visionai.v1.ListInstancesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListInstancesRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListInstancesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListInstancesRequest)
private static final com.google.cloud.visionai.v1.ListInstancesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListInstancesRequest();
}
public static com.google.cloud.visionai.v1.ListInstancesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListInstancesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListInstancesRequest>() {
@java.lang.Override
public ListInstancesRequest 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<ListInstancesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListInstancesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListInstancesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,983 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ListAgentsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3beta1/agent.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3beta1;
/**
*
*
* <pre>
* The response message for
* [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse}
*/
public final class ListAgentsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse)
ListAgentsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAgentsResponse.newBuilder() to construct.
private ListAgentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAgentsResponse() {
agents_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAgentsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ListAgentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ListAgentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.class,
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.Builder.class);
}
public static final int AGENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Agent> agents_;
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Agent> getAgentsList() {
return agents_;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder>
getAgentsOrBuilderList() {
return agents_;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
@java.lang.Override
public int getAgentsCount() {
return agents_.size();
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.Agent getAgents(int index) {
return agents_.get(index);
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder getAgentsOrBuilder(int index) {
return agents_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < agents_.size(); i++) {
output.writeMessage(1, agents_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < agents_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, agents_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse other =
(com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse) obj;
if (!getAgentsList().equals(other.getAgentsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getAgentsCount() > 0) {
hash = (37 * hash) + AGENTS_FIELD_NUMBER;
hash = (53 * hash) + getAgentsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for
* [Agents.ListAgents][google.cloud.dialogflow.cx.v3beta1.Agents.ListAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse)
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ListAgentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ListAgentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.class,
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (agentsBuilder_ == null) {
agents_ = java.util.Collections.emptyList();
} else {
agents_ = null;
agentsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3beta1.AgentProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ListAgentsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse build() {
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse buildPartial() {
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse result =
new com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse result) {
if (agentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
agents_ = java.util.Collections.unmodifiableList(agents_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.agents_ = agents_;
} else {
result.agents_ = agentsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse) {
return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse other) {
if (other == com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse.getDefaultInstance())
return this;
if (agentsBuilder_ == null) {
if (!other.agents_.isEmpty()) {
if (agents_.isEmpty()) {
agents_ = other.agents_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAgentsIsMutable();
agents_.addAll(other.agents_);
}
onChanged();
}
} else {
if (!other.agents_.isEmpty()) {
if (agentsBuilder_.isEmpty()) {
agentsBuilder_.dispose();
agentsBuilder_ = null;
agents_ = other.agents_;
bitField0_ = (bitField0_ & ~0x00000001);
agentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAgentsFieldBuilder()
: null;
} else {
agentsBuilder_.addAllMessages(other.agents_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.dialogflow.cx.v3beta1.Agent m =
input.readMessage(
com.google.cloud.dialogflow.cx.v3beta1.Agent.parser(), extensionRegistry);
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(m);
} else {
agentsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Agent> agents_ =
java.util.Collections.emptyList();
private void ensureAgentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
agents_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3beta1.Agent>(agents_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.Agent,
com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder,
com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder>
agentsBuilder_;
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Agent> getAgentsList() {
if (agentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(agents_);
} else {
return agentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public int getAgentsCount() {
if (agentsBuilder_ == null) {
return agents_.size();
} else {
return agentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.Agent getAgents(int index) {
if (agentsBuilder_ == null) {
return agents_.get(index);
} else {
return agentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder setAgents(int index, com.google.cloud.dialogflow.cx.v3beta1.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.set(index, value);
onChanged();
} else {
agentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder setAgents(
int index, com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.set(index, builderForValue.build());
onChanged();
} else {
agentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder addAgents(com.google.cloud.dialogflow.cx.v3beta1.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.add(value);
onChanged();
} else {
agentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder addAgents(int index, com.google.cloud.dialogflow.cx.v3beta1.Agent value) {
if (agentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAgentsIsMutable();
agents_.add(index, value);
onChanged();
} else {
agentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder addAgents(com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(builderForValue.build());
onChanged();
} else {
agentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder addAgents(
int index, com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder builderForValue) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.add(index, builderForValue.build());
onChanged();
} else {
agentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder addAllAgents(
java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3beta1.Agent> values) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, agents_);
onChanged();
} else {
agentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder clearAgents() {
if (agentsBuilder_ == null) {
agents_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
agentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public Builder removeAgents(int index) {
if (agentsBuilder_ == null) {
ensureAgentsIsMutable();
agents_.remove(index);
onChanged();
} else {
agentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder getAgentsBuilder(int index) {
return getAgentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder getAgentsOrBuilder(int index) {
if (agentsBuilder_ == null) {
return agents_.get(index);
} else {
return agentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder>
getAgentsOrBuilderList() {
if (agentsBuilder_ != null) {
return agentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(agents_);
}
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder addAgentsBuilder() {
return getAgentsFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.cx.v3beta1.Agent.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder addAgentsBuilder(int index) {
return getAgentsFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.cx.v3beta1.Agent.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of agents. There will be a maximum number of items returned based
* on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3beta1.Agent agents = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder>
getAgentsBuilderList() {
return getAgentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.Agent,
com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder,
com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder>
getAgentsFieldBuilder() {
if (agentsBuilder_ == null) {
agentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3beta1.Agent,
com.google.cloud.dialogflow.cx.v3beta1.Agent.Builder,
com.google.cloud.dialogflow.cx.v3beta1.AgentOrBuilder>(
agents_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
agents_ = null;
}
return agentsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse)
private static final com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse();
}
public static com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAgentsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAgentsResponse>() {
@java.lang.Override
public ListAgentsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListAgentsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAgentsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ListAgentsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,283 | java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonTargetInstancesStub.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import static com.google.cloud.compute.v1.TargetInstancesClient.AggregatedListPagedResponse;
import static com.google.cloud.compute.v1.TargetInstancesClient.ListPagedResponse;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshot;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.httpjson.ProtoMessageRequestFormatter;
import com.google.api.gax.httpjson.ProtoMessageResponseParser;
import com.google.api.gax.httpjson.ProtoRestSerializer;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.AggregatedListTargetInstancesRequest;
import com.google.cloud.compute.v1.DeleteTargetInstanceRequest;
import com.google.cloud.compute.v1.GetTargetInstanceRequest;
import com.google.cloud.compute.v1.InsertTargetInstanceRequest;
import com.google.cloud.compute.v1.ListTargetInstancesRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.SetSecurityPolicyTargetInstanceRequest;
import com.google.cloud.compute.v1.TargetInstance;
import com.google.cloud.compute.v1.TargetInstanceAggregatedList;
import com.google.cloud.compute.v1.TargetInstanceList;
import com.google.cloud.compute.v1.TestIamPermissionsTargetInstanceRequest;
import com.google.cloud.compute.v1.TestPermissionsResponse;
import com.google.protobuf.TypeRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST stub implementation for the TargetInstances service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class HttpJsonTargetInstancesStub extends TargetInstancesStub {
private static final TypeRegistry typeRegistry =
TypeRegistry.newBuilder().add(Operation.getDescriptor()).build();
private static final ApiMethodDescriptor<
AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>
aggregatedListMethodDescriptor =
ApiMethodDescriptor
.<AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/AggregatedList")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<AggregatedListTargetInstancesRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/aggregated/targetInstances",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<AggregatedListTargetInstancesRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<AggregatedListTargetInstancesRequest> serializer =
ProtoRestSerializer.create();
if (request.hasFilter()) {
serializer.putQueryParam(fields, "filter", request.getFilter());
}
if (request.hasIncludeAllScopes()) {
serializer.putQueryParam(
fields, "includeAllScopes", request.getIncludeAllScopes());
}
if (request.hasMaxResults()) {
serializer.putQueryParam(
fields, "maxResults", request.getMaxResults());
}
if (request.hasOrderBy()) {
serializer.putQueryParam(fields, "orderBy", request.getOrderBy());
}
if (request.hasPageToken()) {
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
}
if (request.hasReturnPartialSuccess()) {
serializer.putQueryParam(
fields,
"returnPartialSuccess",
request.getReturnPartialSuccess());
}
if (request.hasServiceProjectNumber()) {
serializer.putQueryParam(
fields,
"serviceProjectNumber",
request.getServiceProjectNumber());
}
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<TargetInstanceAggregatedList>newBuilder()
.setDefaultInstance(TargetInstanceAggregatedList.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<DeleteTargetInstanceRequest, Operation>
deleteMethodDescriptor =
ApiMethodDescriptor.<DeleteTargetInstanceRequest, Operation>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/Delete")
.setHttpMethod("DELETE")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<DeleteTargetInstanceRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances/{targetInstance}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<DeleteTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(
fields, "targetInstance", request.getTargetInstance());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<DeleteTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
if (request.hasRequestId()) {
serializer.putQueryParam(fields, "requestId", request.getRequestId());
}
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<Operation>newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.setOperationSnapshotFactory(
(DeleteTargetInstanceRequest request, Operation response) -> {
StringBuilder opName = new StringBuilder(response.getName());
opName.append(":").append(request.getProject());
opName.append(":").append(request.getZone());
return HttpJsonOperationSnapshot.newBuilder()
.setName(opName.toString())
.setMetadata(response)
.setDone(Status.DONE.equals(response.getStatus()))
.setResponse(response)
.setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage())
.build();
})
.build();
private static final ApiMethodDescriptor<GetTargetInstanceRequest, TargetInstance>
getMethodDescriptor =
ApiMethodDescriptor.<GetTargetInstanceRequest, TargetInstance>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/Get")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<GetTargetInstanceRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances/{targetInstance}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<GetTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(
fields, "targetInstance", request.getTargetInstance());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<GetTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<TargetInstance>newBuilder()
.setDefaultInstance(TargetInstance.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<InsertTargetInstanceRequest, Operation>
insertMethodDescriptor =
ApiMethodDescriptor.<InsertTargetInstanceRequest, Operation>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/Insert")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<InsertTargetInstanceRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<InsertTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<InsertTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
if (request.hasRequestId()) {
serializer.putQueryParam(fields, "requestId", request.getRequestId());
}
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody(
"targetInstanceResource",
request.getTargetInstanceResource(),
false))
.build())
.setResponseParser(
ProtoMessageResponseParser.<Operation>newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.setOperationSnapshotFactory(
(InsertTargetInstanceRequest request, Operation response) -> {
StringBuilder opName = new StringBuilder(response.getName());
opName.append(":").append(request.getProject());
opName.append(":").append(request.getZone());
return HttpJsonOperationSnapshot.newBuilder()
.setName(opName.toString())
.setMetadata(response)
.setDone(Status.DONE.equals(response.getStatus()))
.setResponse(response)
.setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage())
.build();
})
.build();
private static final ApiMethodDescriptor<ListTargetInstancesRequest, TargetInstanceList>
listMethodDescriptor =
ApiMethodDescriptor.<ListTargetInstancesRequest, TargetInstanceList>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/List")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<ListTargetInstancesRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<ListTargetInstancesRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<ListTargetInstancesRequest> serializer =
ProtoRestSerializer.create();
if (request.hasFilter()) {
serializer.putQueryParam(fields, "filter", request.getFilter());
}
if (request.hasMaxResults()) {
serializer.putQueryParam(
fields, "maxResults", request.getMaxResults());
}
if (request.hasOrderBy()) {
serializer.putQueryParam(fields, "orderBy", request.getOrderBy());
}
if (request.hasPageToken()) {
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
}
if (request.hasReturnPartialSuccess()) {
serializer.putQueryParam(
fields,
"returnPartialSuccess",
request.getReturnPartialSuccess());
}
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<TargetInstanceList>newBuilder()
.setDefaultInstance(TargetInstanceList.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<SetSecurityPolicyTargetInstanceRequest, Operation>
setSecurityPolicyMethodDescriptor =
ApiMethodDescriptor.<SetSecurityPolicyTargetInstanceRequest, Operation>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/SetSecurityPolicy")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<SetSecurityPolicyTargetInstanceRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances/{targetInstance}/setSecurityPolicy",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<SetSecurityPolicyTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(
fields, "targetInstance", request.getTargetInstance());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<SetSecurityPolicyTargetInstanceRequest> serializer =
ProtoRestSerializer.create();
if (request.hasRequestId()) {
serializer.putQueryParam(fields, "requestId", request.getRequestId());
}
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody(
"securityPolicyReferenceResource",
request.getSecurityPolicyReferenceResource(),
false))
.build())
.setResponseParser(
ProtoMessageResponseParser.<Operation>newBuilder()
.setDefaultInstance(Operation.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.setOperationSnapshotFactory(
(SetSecurityPolicyTargetInstanceRequest request, Operation response) -> {
StringBuilder opName = new StringBuilder(response.getName());
opName.append(":").append(request.getProject());
opName.append(":").append(request.getZone());
return HttpJsonOperationSnapshot.newBuilder()
.setName(opName.toString())
.setMetadata(response)
.setDone(Status.DONE.equals(response.getStatus()))
.setResponse(response)
.setError(response.getHttpErrorStatusCode(), response.getHttpErrorMessage())
.build();
})
.build();
private static final ApiMethodDescriptor<
TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>
testIamPermissionsMethodDescriptor =
ApiMethodDescriptor
.<TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>newBuilder()
.setFullMethodName("google.cloud.compute.v1.TargetInstances/TestIamPermissions")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<TestIamPermissionsTargetInstanceRequest>newBuilder()
.setPath(
"/compute/v1/projects/{project}/zones/{zone}/targetInstances/{resource}/testIamPermissions",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<TestIamPermissionsTargetInstanceRequest>
serializer = ProtoRestSerializer.create();
serializer.putPathParam(fields, "project", request.getProject());
serializer.putPathParam(fields, "resource", request.getResource());
serializer.putPathParam(fields, "zone", request.getZone());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<TestIamPermissionsTargetInstanceRequest>
serializer = ProtoRestSerializer.create();
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody(
"testPermissionsRequestResource",
request.getTestPermissionsRequestResource(),
false))
.build())
.setResponseParser(
ProtoMessageResponseParser.<TestPermissionsResponse>newBuilder()
.setDefaultInstance(TestPermissionsResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private final UnaryCallable<AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>
aggregatedListCallable;
private final UnaryCallable<AggregatedListTargetInstancesRequest, AggregatedListPagedResponse>
aggregatedListPagedCallable;
private final UnaryCallable<DeleteTargetInstanceRequest, Operation> deleteCallable;
private final OperationCallable<DeleteTargetInstanceRequest, Operation, Operation>
deleteOperationCallable;
private final UnaryCallable<GetTargetInstanceRequest, TargetInstance> getCallable;
private final UnaryCallable<InsertTargetInstanceRequest, Operation> insertCallable;
private final OperationCallable<InsertTargetInstanceRequest, Operation, Operation>
insertOperationCallable;
private final UnaryCallable<ListTargetInstancesRequest, TargetInstanceList> listCallable;
private final UnaryCallable<ListTargetInstancesRequest, ListPagedResponse> listPagedCallable;
private final UnaryCallable<SetSecurityPolicyTargetInstanceRequest, Operation>
setSecurityPolicyCallable;
private final OperationCallable<SetSecurityPolicyTargetInstanceRequest, Operation, Operation>
setSecurityPolicyOperationCallable;
private final UnaryCallable<TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>
testIamPermissionsCallable;
private final BackgroundResource backgroundResources;
private final HttpJsonZoneOperationsStub httpJsonOperationsStub;
private final HttpJsonStubCallableFactory callableFactory;
public static final HttpJsonTargetInstancesStub create(TargetInstancesStubSettings settings)
throws IOException {
return new HttpJsonTargetInstancesStub(settings, ClientContext.create(settings));
}
public static final HttpJsonTargetInstancesStub create(ClientContext clientContext)
throws IOException {
return new HttpJsonTargetInstancesStub(
TargetInstancesStubSettings.newBuilder().build(), clientContext);
}
public static final HttpJsonTargetInstancesStub create(
ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException {
return new HttpJsonTargetInstancesStub(
TargetInstancesStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of HttpJsonTargetInstancesStub, 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 HttpJsonTargetInstancesStub(
TargetInstancesStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new HttpJsonTargetInstancesCallableFactory());
}
/**
* Constructs an instance of HttpJsonTargetInstancesStub, 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 HttpJsonTargetInstancesStub(
TargetInstancesStubSettings settings,
ClientContext clientContext,
HttpJsonStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.httpJsonOperationsStub = HttpJsonZoneOperationsStub.create(clientContext, callableFactory);
HttpJsonCallSettings<AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>
aggregatedListTransportSettings =
HttpJsonCallSettings
.<AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>newBuilder()
.setMethodDescriptor(aggregatedListMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
return builder.build();
})
.build();
HttpJsonCallSettings<DeleteTargetInstanceRequest, Operation> deleteTransportSettings =
HttpJsonCallSettings.<DeleteTargetInstanceRequest, Operation>newBuilder()
.setMethodDescriptor(deleteMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("target_instance", String.valueOf(request.getTargetInstance()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
HttpJsonCallSettings<GetTargetInstanceRequest, TargetInstance> getTransportSettings =
HttpJsonCallSettings.<GetTargetInstanceRequest, TargetInstance>newBuilder()
.setMethodDescriptor(getMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("target_instance", String.valueOf(request.getTargetInstance()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
HttpJsonCallSettings<InsertTargetInstanceRequest, Operation> insertTransportSettings =
HttpJsonCallSettings.<InsertTargetInstanceRequest, Operation>newBuilder()
.setMethodDescriptor(insertMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
HttpJsonCallSettings<ListTargetInstancesRequest, TargetInstanceList> listTransportSettings =
HttpJsonCallSettings.<ListTargetInstancesRequest, TargetInstanceList>newBuilder()
.setMethodDescriptor(listMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
HttpJsonCallSettings<SetSecurityPolicyTargetInstanceRequest, Operation>
setSecurityPolicyTransportSettings =
HttpJsonCallSettings.<SetSecurityPolicyTargetInstanceRequest, Operation>newBuilder()
.setMethodDescriptor(setSecurityPolicyMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("target_instance", String.valueOf(request.getTargetInstance()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
HttpJsonCallSettings<TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>
testIamPermissionsTransportSettings =
HttpJsonCallSettings
.<TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>newBuilder()
.setMethodDescriptor(testIamPermissionsMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("project", String.valueOf(request.getProject()));
builder.add("resource", String.valueOf(request.getResource()));
builder.add("zone", String.valueOf(request.getZone()));
return builder.build();
})
.build();
this.aggregatedListCallable =
callableFactory.createUnaryCallable(
aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext);
this.aggregatedListPagedCallable =
callableFactory.createPagedCallable(
aggregatedListTransportSettings, settings.aggregatedListSettings(), clientContext);
this.deleteCallable =
callableFactory.createUnaryCallable(
deleteTransportSettings, settings.deleteSettings(), clientContext);
this.deleteOperationCallable =
callableFactory.createOperationCallable(
deleteTransportSettings,
settings.deleteOperationSettings(),
clientContext,
httpJsonOperationsStub);
this.getCallable =
callableFactory.createUnaryCallable(
getTransportSettings, settings.getSettings(), clientContext);
this.insertCallable =
callableFactory.createUnaryCallable(
insertTransportSettings, settings.insertSettings(), clientContext);
this.insertOperationCallable =
callableFactory.createOperationCallable(
insertTransportSettings,
settings.insertOperationSettings(),
clientContext,
httpJsonOperationsStub);
this.listCallable =
callableFactory.createUnaryCallable(
listTransportSettings, settings.listSettings(), clientContext);
this.listPagedCallable =
callableFactory.createPagedCallable(
listTransportSettings, settings.listSettings(), clientContext);
this.setSecurityPolicyCallable =
callableFactory.createUnaryCallable(
setSecurityPolicyTransportSettings,
settings.setSecurityPolicySettings(),
clientContext);
this.setSecurityPolicyOperationCallable =
callableFactory.createOperationCallable(
setSecurityPolicyTransportSettings,
settings.setSecurityPolicyOperationSettings(),
clientContext,
httpJsonOperationsStub);
this.testIamPermissionsCallable =
callableFactory.createUnaryCallable(
testIamPermissionsTransportSettings,
settings.testIamPermissionsSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
@InternalApi
public static List<ApiMethodDescriptor> getMethodDescriptors() {
List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>();
methodDescriptors.add(aggregatedListMethodDescriptor);
methodDescriptors.add(deleteMethodDescriptor);
methodDescriptors.add(getMethodDescriptor);
methodDescriptors.add(insertMethodDescriptor);
methodDescriptors.add(listMethodDescriptor);
methodDescriptors.add(setSecurityPolicyMethodDescriptor);
methodDescriptors.add(testIamPermissionsMethodDescriptor);
return methodDescriptors;
}
@Override
public UnaryCallable<AggregatedListTargetInstancesRequest, TargetInstanceAggregatedList>
aggregatedListCallable() {
return aggregatedListCallable;
}
@Override
public UnaryCallable<AggregatedListTargetInstancesRequest, AggregatedListPagedResponse>
aggregatedListPagedCallable() {
return aggregatedListPagedCallable;
}
@Override
public UnaryCallable<DeleteTargetInstanceRequest, Operation> deleteCallable() {
return deleteCallable;
}
@Override
public OperationCallable<DeleteTargetInstanceRequest, Operation, Operation>
deleteOperationCallable() {
return deleteOperationCallable;
}
@Override
public UnaryCallable<GetTargetInstanceRequest, TargetInstance> getCallable() {
return getCallable;
}
@Override
public UnaryCallable<InsertTargetInstanceRequest, Operation> insertCallable() {
return insertCallable;
}
@Override
public OperationCallable<InsertTargetInstanceRequest, Operation, Operation>
insertOperationCallable() {
return insertOperationCallable;
}
@Override
public UnaryCallable<ListTargetInstancesRequest, TargetInstanceList> listCallable() {
return listCallable;
}
@Override
public UnaryCallable<ListTargetInstancesRequest, ListPagedResponse> listPagedCallable() {
return listPagedCallable;
}
@Override
public UnaryCallable<SetSecurityPolicyTargetInstanceRequest, Operation>
setSecurityPolicyCallable() {
return setSecurityPolicyCallable;
}
@Override
public OperationCallable<SetSecurityPolicyTargetInstanceRequest, Operation, Operation>
setSecurityPolicyOperationCallable() {
return setSecurityPolicyOperationCallable;
}
@Override
public UnaryCallable<TestIamPermissionsTargetInstanceRequest, TestPermissionsResponse>
testIamPermissionsCallable() {
return testIamPermissionsCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
apache/incubator-kie-drools | 38,554 | kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.dmn.feel.codegen.feel11;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.BooleanLiteralExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.stmt.ThrowStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import org.kie.dmn.feel.lang.Type;
import org.kie.dmn.feel.lang.ast.AtLiteralNode;
import org.kie.dmn.feel.lang.ast.BaseNode;
import org.kie.dmn.feel.lang.ast.BetweenNode;
import org.kie.dmn.feel.lang.ast.BooleanNode;
import org.kie.dmn.feel.lang.ast.CTypeNode;
import org.kie.dmn.feel.lang.ast.ContextEntryNode;
import org.kie.dmn.feel.lang.ast.ContextNode;
import org.kie.dmn.feel.lang.ast.ContextTypeNode;
import org.kie.dmn.feel.lang.ast.DashNode;
import org.kie.dmn.feel.lang.ast.DescendantExpressionNode;
import org.kie.dmn.feel.lang.ast.FilterExpressionNode;
import org.kie.dmn.feel.lang.ast.ForExpressionNode;
import org.kie.dmn.feel.lang.ast.FormalParameterNode;
import org.kie.dmn.feel.lang.ast.FunctionDefNode;
import org.kie.dmn.feel.lang.ast.FunctionInvocationNode;
import org.kie.dmn.feel.lang.ast.FunctionTypeNode;
import org.kie.dmn.feel.lang.ast.IfExpressionNode;
import org.kie.dmn.feel.lang.ast.InNode;
import org.kie.dmn.feel.lang.ast.InfixOpNode;
import org.kie.dmn.feel.lang.ast.InstanceOfNode;
import org.kie.dmn.feel.lang.ast.IterationContextNode;
import org.kie.dmn.feel.lang.ast.ListNode;
import org.kie.dmn.feel.lang.ast.ListTypeNode;
import org.kie.dmn.feel.lang.ast.NameDefNode;
import org.kie.dmn.feel.lang.ast.NameRefNode;
import org.kie.dmn.feel.lang.ast.NamedParameterNode;
import org.kie.dmn.feel.lang.ast.NullNode;
import org.kie.dmn.feel.lang.ast.NumberNode;
import org.kie.dmn.feel.lang.ast.PathExpressionNode;
import org.kie.dmn.feel.lang.ast.QualifiedNameNode;
import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode;
import org.kie.dmn.feel.lang.ast.RangeNode;
import org.kie.dmn.feel.lang.ast.RangeTypeNode;
import org.kie.dmn.feel.lang.ast.SignedUnaryNode;
import org.kie.dmn.feel.lang.ast.StringNode;
import org.kie.dmn.feel.lang.ast.TemporalConstantNode;
import org.kie.dmn.feel.lang.ast.TypeNode;
import org.kie.dmn.feel.lang.ast.UnaryTestListNode;
import org.kie.dmn.feel.lang.ast.UnaryTestNode;
import org.kie.dmn.feel.lang.ast.UndefinedValueNode;
import org.kie.dmn.feel.lang.impl.JavaBackedType;
import org.kie.dmn.feel.lang.impl.MapBackedType;
import org.kie.dmn.feel.lang.types.AliasFEELType;
import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.feel.runtime.FEELFunction;
import org.kie.dmn.feel.util.CodegenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType;
import static com.github.javaparser.StaticJavaParser.parseExpression;
import static com.github.javaparser.utils.StringEscapeUtils.escapeJava;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.ADDFIELD_S;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.HASHMAP_CT;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.ILLEGALSTATEEXCEPTION_CT;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.INSTANCE_S;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.MAP_CT;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.OF_S;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.PUT_S;
import static org.kie.dmn.feel.codegen.feel11.CodegenConstants.VAR_S;
import static org.kie.dmn.feel.codegen.feel11.Constants.BUILTINTYPE_E;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.ALIASFEELTYPE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.ATLITERALNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.BETWEENNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.BOOLEANNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.CONTEXTENTRYNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.CONTEXTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.CONTEXTTYPENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.CTYPENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.DASHNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.DESCENDANTEXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.DETERMINEOPERATOR_S;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FILTEREXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FOREXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FORMALPARAMETERNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FUNCTIONDEFNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FUNCTIONINVOCATIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.FUNCTIONTYPENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.GETBIGDECIMALORNULL_S;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.IFEXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.INFIXOPERATOR_N;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.INFIXOPNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.INNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.INSTANCEOFNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.ITERATIONCONTEXTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.JAVABACKEDTYPE_N;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.LISTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.LISTTYPENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.MAPBACKEDTYPE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NAMEDEFNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NAMEDPARAMETERNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NAMEREFNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NULLNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NUMBEREVALHELPER_N;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.NUMBERNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.PATHEXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUALIFIEDNAMENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUANTIFIEDEXPRESSIONNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGETYPENODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.SIGNEDUNARYNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.STRINGNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TEMPORALCONSTANTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TYPE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTLISTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTNODE_CT;
import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNDEFINEDVALUENODE_CT;
import static org.kie.dmn.feel.util.CodegenUtils.getEnumExpression;
import static org.kie.dmn.feel.util.CodegenUtils.getListExpression;
import static org.kie.dmn.feel.util.CodegenUtils.getStringLiteralExpr;
import static org.kie.dmn.feel.util.CodegenUtils.getVariableDeclaratorWithFieldAccessExpr;
import static org.kie.dmn.feel.util.CodegenUtils.getVariableDeclaratorWithObjectCreation;
public class ASTCompilerHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(ASTCompilerHelper.class);
private static final String EXTENDED_FUNCTION_PACKAGE = "org.kie.dmn.feel.runtime.functions.extended";
private final ASTCompilerVisitor astCompilerVisitor;
private final BlockStmt toPopulate;
private final AtomicInteger variableCounter;
private final Map<BaseNode, NameExpr> baseNodeCache;
private final Map<Type, Expression> typeCache;
private final Map<Object, NameExpr> objectCache;
private AtomicReference<String> lastVariableName = new AtomicReference<>();
public ASTCompilerHelper(ASTCompilerVisitor astCompilerVisitor) {
this.astCompilerVisitor = astCompilerVisitor;
toPopulate = new BlockStmt();
variableCounter = new AtomicInteger(0);
baseNodeCache = new ConcurrentHashMap<>();
typeCache = new ConcurrentHashMap<>();
objectCache = new ConcurrentHashMap<>();
}
public BlockStmt add(AtLiteralNode n) {
Expression stringLiteralExpression = getNodeExpression(n.getStringLiteral());
return addVariableDeclaratorWithObjectCreation(ATLITERALNODE_CT, NodeList.nodeList(stringLiteralExpression),
n.getText());
}
public BlockStmt add(BetweenNode n) {
Expression valueExpression = getNodeExpression(n.getValue());
Expression startExpression = getNodeExpression(n.getStart());
Expression endExpression = getNodeExpression(n.getEnd());
return addVariableDeclaratorWithObjectCreation(BETWEENNODE_CT, NodeList.nodeList(valueExpression,
startExpression,
endExpression), n.getText());
}
public BlockStmt add(BooleanNode n) {
Expression valueExpression = new BooleanLiteralExpr(n.getValue());
return addVariableDeclaratorWithObjectCreation(BOOLEANNODE_CT, NodeList.nodeList(valueExpression), n.getText());
}
public BlockStmt add(ContextEntryNode n) {
Expression nameExpression = getNodeExpression(n.getName());
Expression valueExpression = getNodeExpression(n.getValue());
return addVariableDeclaratorWithObjectCreation(CONTEXTENTRYNODE_CT, NodeList.nodeList(nameExpression,
valueExpression),
n.getText());
}
public BlockStmt add(ContextNode n) {
List entryNodesExpressions = n.getEntries().stream().map(entryNode -> getNodeExpression(entryNode))
.toList();
return addVariableDeclaratorWithObjectCreation(CONTEXTNODE_CT,
NodeList.nodeList(getListExpression(entryNodesExpressions)),
n.getText());
}
public BlockStmt add(ContextTypeNode n) {
Map<Expression, Expression> genExpressions = new HashMap<>(); // THe key is the StringLiteralExpr of the
// original key; the value is the NameExpr pointing at generated variable
for (Map.Entry<String, TypeNode> kv : n.getGen().entrySet()) {
genExpressions.put(new StringLiteralExpr(kv.getKey()), getNodeExpression(kv.getValue()));
}
// Creating the map
String mapVariableName = getNextVariableName();
final VariableDeclarator mapVariableDeclarator =
new VariableDeclarator(MAP_CT, mapVariableName);
final ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr(null, HASHMAP_CT, NodeList.nodeList());
mapVariableDeclarator.setInitializer(objectCreationExpr);
VariableDeclarationExpr mapVariableDeclarationExpr = new VariableDeclarationExpr(mapVariableDeclarator);
addExpression(mapVariableDeclarationExpr, mapVariableName);
// Populating the map
Expression mapVariableExpression = new NameExpr(mapVariableName);
genExpressions.forEach((key, value) -> {
MethodCallExpr putExpression = new MethodCallExpr(mapVariableExpression, PUT_S);
putExpression.addArgument(key);
putExpression.addArgument(value);
addExpression(putExpression);
});
return addVariableDeclaratorWithObjectCreation(CONTEXTTYPENODE_CT, NodeList.nodeList(mapVariableExpression),
n.getText());
}
public BlockStmt add(CTypeNode n) {
if (!(n.getType() instanceof BuiltInType)) {
throw new UnsupportedOperationException();
}
BuiltInType feelCType = (BuiltInType) n.getType();
Expression typeExpression = new FieldAccessExpr(BUILTINTYPE_E, feelCType.name());
return addVariableDeclaratorWithObjectCreation(CTYPENODE_CT, NodeList.nodeList(typeExpression), n.getText());
}
public BlockStmt add(DashNode n) {
return addVariableDeclaratorWithObjectCreation(DASHNODE_CT, NodeList.nodeList(), n.getText());
}
public BlockStmt add(DescendantExpressionNode n) {
Expression expressionExpression = getNodeExpression(n.getExpression());
Expression nameExpression = getNodeExpression(n.getName());
return addVariableDeclaratorWithObjectCreation(DESCENDANTEXPRESSIONNODE_CT,
NodeList.nodeList(expressionExpression, nameExpression),
n.getText());
}
public BlockStmt add(ForExpressionNode n) {
List iterationContextsExpressions =
n.getIterationContexts().stream().map(elementNode -> getNodeExpression(elementNode))
.toList();
Expression expressionExpression = getNodeExpression(n.getExpression());
return addVariableDeclaratorWithObjectCreation(FOREXPRESSIONNODE_CT,
NodeList.nodeList(getListExpression(iterationContextsExpressions),
expressionExpression),
n.getText());
}
public BlockStmt add(FilterExpressionNode n) {
Expression expressionExpression = getNodeExpression(n.getExpression());
Expression filterExpression = getNodeExpression(n.getFilter());
return addVariableDeclaratorWithObjectCreation(FILTEREXPRESSIONNODE_CT, NodeList.nodeList(expressionExpression,
filterExpression),
n.getText());
}
public BlockStmt add(FormalParameterNode n) {
Expression nameExpression = getNodeExpression(n.getName());
Expression typeExpression = getNodeExpression(n.getType());
return addVariableDeclaratorWithObjectCreation(FORMALPARAMETERNODE_CT, NodeList.nodeList(nameExpression,
typeExpression),
n.getText());
}
public BlockStmt add(FunctionDefNode n) {
List formalParametersExpressions = n.getFormalParameters().stream()
.map(elementNode -> getNodeExpression(elementNode))
.toList();
Expression bodyExpression = getNodeExpression(n.getBody());
return addVariableDeclaratorWithObjectCreation(FUNCTIONDEFNODE_CT,
NodeList.nodeList(getListExpression(formalParametersExpressions),
new BooleanLiteralExpr(n.isExternal()),
bodyExpression),
n.getText());
}
public BlockStmt add(FunctionInvocationNode n) {
Expression nameExpression = getNodeExpression(n.getName());
Expression paramsExpression = getNodeExpression(n.getParams());
Expression tcFoldedExpression = getNodeExpression(n.getTcFolded());
return addVariableDeclaratorWithObjectCreation(FUNCTIONINVOCATIONNODE_CT, NodeList.nodeList(nameExpression,
paramsExpression,
tcFoldedExpression), n.getText());
}
public BlockStmt add(FunctionTypeNode n) {
List argTypesExpressions = n.getArgTypes().stream().map(argTypeNode -> getNodeExpression(argTypeNode))
.toList();
Expression retTypeExpression = getNodeExpression(n.getRetType());
return addVariableDeclaratorWithObjectCreation(FUNCTIONTYPENODE_CT,
NodeList.nodeList(getListExpression(argTypesExpressions),
retTypeExpression),
n.getText());
}
public BlockStmt add(IfExpressionNode n) {
Expression conditionExpression = getNodeExpression(n.getCondition());
Expression thenExpression = getNodeExpression(n.getThenExpression());
Expression elseExpression = getNodeExpression(n.getElseExpression());
return addVariableDeclaratorWithObjectCreation(IFEXPRESSIONNODE_CT, NodeList.nodeList(conditionExpression,
thenExpression,
elseExpression),
n.getText());
}
public BlockStmt add(InfixOpNode n) {
Expression determineOperatorExpression = new MethodCallExpr(INFIXOPERATOR_N, DETERMINEOPERATOR_S,
new NodeList<>(new StringLiteralExpr(n.getOperator().getSymbol())));
Expression leftExpression = getNodeExpression(n.getLeft());
Expression rightExpression = getNodeExpression(n.getRight());
return addVariableDeclaratorWithObjectCreation(INFIXOPNODE_CT, NodeList.nodeList(determineOperatorExpression,
leftExpression,
rightExpression), n.getText());
}
public BlockStmt add(InNode n) {
Expression valueExpression = getNodeExpression(n.getValue());
Expression exprsExpression = getNodeExpression(n.getExprs());
return addVariableDeclaratorWithObjectCreation(INNODE_CT, NodeList.nodeList(valueExpression, exprsExpression)
, n.getText());
}
public BlockStmt add(InstanceOfNode n) {
Expression expressionExpression = getNodeExpression(n.getExpression());
Expression typeExpression = getNodeExpression(n.getType());
return addVariableDeclaratorWithObjectCreation(INSTANCEOFNODE_CT, NodeList.nodeList(expressionExpression,
typeExpression),
n.getText());
}
public BlockStmt add(IterationContextNode n) {
Expression nameExpression = getNodeExpression(n.getName());
Expression expressionExpression = getNodeExpression(n.getExpression());
Expression rangeEndExprExpression = getNodeExpression(n.getRangeEndExpr());
return addVariableDeclaratorWithObjectCreation(ITERATIONCONTEXTNODE_CT, NodeList.nodeList(nameExpression,
expressionExpression, rangeEndExprExpression), n.getText());
}
public BlockStmt add(ListNode n) {
List elements = n.getElements().stream().map(elementNode -> getNodeExpression(elementNode))
.toList();
return addVariableDeclaratorWithObjectCreation(LISTNODE_CT, NodeList.nodeList(getListExpression(elements)),
n.getText());
}
public BlockStmt add(ListTypeNode n) {
Expression genTypeNodeExpression = getNodeExpression(n.getGenTypeNode());
return addVariableDeclaratorWithObjectCreation(LISTTYPENODE_CT, NodeList.nodeList(genTypeNodeExpression),
n.getText());
}
public BlockStmt add(NameDefNode n) {
List partsExpressions = n.getParts().stream().map(StringLiteralExpr::new)
.toList();
Expression nameExpression = n.getName() != null ? new StringLiteralExpr(n.getName()) : new NullLiteralExpr();
return addVariableDeclaratorWithObjectCreation(NAMEDEFNODE_CT,
NodeList.nodeList(getListExpression(partsExpressions),
nameExpression), n.getText());
}
public BlockStmt add(NamedParameterNode n) {
Expression nameExpression = getNodeExpression(n.getName());
Expression expressionExpression = getNodeExpression(n.getExpression());
return addVariableDeclaratorWithObjectCreation(NAMEDPARAMETERNODE_CT, NodeList.nodeList(nameExpression,
expressionExpression)
, n.getText());
}
public BlockStmt add(NameRefNode n) {
Expression typeExpression = getTypeExpression(n.getResultType());
return addVariableDeclaratorWithObjectCreation(NAMEREFNODE_CT, NodeList.nodeList(typeExpression), n.getText());
}
public BlockStmt add(NullNode n) {
return addVariableDeclaratorWithObjectCreation(NULLNODE_CT, NodeList.nodeList(), n.getText());
}
public BlockStmt add(NumberNode n) {
MethodCallExpr valueExpression = new MethodCallExpr(NUMBEREVALHELPER_N, GETBIGDECIMALORNULL_S,
NodeList.nodeList(new StringLiteralExpr(n.getText())));
return addVariableDeclaratorWithObjectCreation(NUMBERNODE_CT, NodeList.nodeList(valueExpression), n.getText());
}
public BlockStmt add(PathExpressionNode n) {
Expression expressionExpression = getNodeExpression(n.getExpression());
Expression nameExpression = getNodeExpression(n.getName());
return addVariableDeclaratorWithObjectCreation(PATHEXPRESSIONNODE_CT, NodeList.nodeList(expressionExpression,
nameExpression),
n.getText());
}
public BlockStmt add(QualifiedNameNode n) {
List partsExpressions = n.getParts().stream().map(partNode -> getNodeExpression(partNode))
.toList();
Expression typeExpression = getTypeExpression(n.getResultType());
return addVariableDeclaratorWithObjectCreation(QUALIFIEDNAMENODE_CT,
NodeList.nodeList(getListExpression(partsExpressions),
typeExpression),
n.getText());
}
public BlockStmt add(QuantifiedExpressionNode n) {
Expression quantifierExpression = getEnumExpression(n.getQuantifier());
List iterationContextsExpressions =
n.getIterationContexts().stream().map(iterationContextNode -> getNodeExpression(iterationContextNode))
.toList();
Expression expressionExpression = getNodeExpression(n.getExpression());
return addVariableDeclaratorWithObjectCreation(QUANTIFIEDEXPRESSIONNODE_CT,
NodeList.nodeList(quantifierExpression,
getListExpression(iterationContextsExpressions),
expressionExpression), n.getText());
}
public BlockStmt add(RangeNode n) {
Expression lowerBoundExpression = getEnumExpression(n.getLowerBound());
Expression upperBoundExpression = getEnumExpression(n.getUpperBound());
Expression startExpression = getNodeExpression(n.getStart());
Expression endExpression = getNodeExpression(n.getEnd());
return addVariableDeclaratorWithObjectCreation(RANGENODE_CT, NodeList.nodeList(lowerBoundExpression,
upperBoundExpression,
startExpression,
endExpression), n.getText());
}
public BlockStmt add(RangeTypeNode n) {
Expression genTypeNodeExpression = getNodeExpression(n.getGenericTypeNode());
return addVariableDeclaratorWithObjectCreation(RANGETYPENODE_CT, NodeList.nodeList(genTypeNodeExpression),
n.getText());
}
public BlockStmt add(SignedUnaryNode n) {
Expression signExpression = getEnumExpression(n.getSign());
Expression expressionExpression = getNodeExpression(n.getExpression());
return addVariableDeclaratorWithObjectCreation(SIGNEDUNARYNODE_CT, NodeList.nodeList(signExpression,
expressionExpression),
n.getText());
}
public BlockStmt add(StringNode n) {
return addVariableDeclaratorWithObjectCreation(STRINGNODE_CT, NodeList.nodeList(),
n.getText());
}
public BlockStmt add(TemporalConstantNode n) {
Expression valueExpression = getObjectExpression(n.getValue());
FEELFunction fn = n.getFn();
Expression fnVariableNameExpression;
if (fn != null) {
Class fnClass = fn.getClass();
ClassOrInterfaceType fn_CT = parseClassOrInterfaceType(fnClass.getCanonicalName());
Expression fn_N = new NameExpr(fnClass.getCanonicalName());
addVariableDeclaratorWithWithFieldAccess(fn_CT, INSTANCE_S, fn_N);
fnVariableNameExpression = new NameExpr(lastVariableName.get());
} else {
fnVariableNameExpression = new NullLiteralExpr();
}
List paramsExpressions = n.getParams().stream().map(param -> getObjectExpression(param)).toList();
return addVariableDeclaratorWithObjectCreation(TEMPORALCONSTANTNODE_CT, NodeList.nodeList(valueExpression,
fnVariableNameExpression, getListExpression(paramsExpressions)), n.getText());
}
public BlockStmt add(UnaryTestListNode n) {
List elementsExpressions = n.getElements().stream().map(elementNode -> getNodeExpression(elementNode))
.toList();
Expression stateExpression = getEnumExpression(n.getState());
return addVariableDeclaratorWithObjectCreation(UNARYTESTLISTNODE_CT,
NodeList.nodeList(getListExpression(elementsExpressions),
stateExpression),
n.getText());
}
public BlockStmt add(UnaryTestNode n) {
Expression opExpression = getEnumExpression(n.getOperator());
Expression valueExpression = getNodeExpression(n.getValue());
return addVariableDeclaratorWithObjectCreation(UNARYTESTNODE_CT, NodeList.nodeList(opExpression,
valueExpression),
n.getText());
}
public BlockStmt add(UndefinedValueNode n) {
return addVariableDeclaratorWithObjectCreation(UNDEFINEDVALUENODE_CT, NodeList.nodeList());
}
public String getLastVariableName() {
return lastVariableName.get();
}
public BlockStmt returnError(String errorMessage) {
ObjectCreationExpr illegalStateExceptionExpression = new ObjectCreationExpr(null, ILLEGALSTATEEXCEPTION_CT,
NodeList.nodeList(getStringLiteralExpr(errorMessage)));
ThrowStmt throwStmt = new ThrowStmt();
throwStmt.setExpression(illegalStateExceptionExpression);
return addStatement(throwStmt);
}
private String getNextVariableName() {
return String.format("%s_%d", VAR_S, variableCounter.getAndIncrement());
}
private BlockStmt addVariableDeclaratorWithObjectCreation(ClassOrInterfaceType variableType,
NodeList<Expression> arguments, String text) {
Expression textExpression = text != null ? new StringLiteralExpr(escapeJava(text)) : new NullLiteralExpr();
arguments.add(textExpression);
return addVariableDeclaratorWithObjectCreation(variableType, arguments);
}
private BlockStmt addVariableDeclaratorWithObjectCreation(ClassOrInterfaceType variableType,
NodeList<Expression> arguments) {
String variableName = getNextVariableName();
final VariableDeclarationExpr toAdd = getVariableDeclaratorWithObjectCreation(variableName, variableType,
arguments);
return addExpression(toAdd, variableName);
}
private BlockStmt addVariableDeclaratorWithWithFieldAccess(ClassOrInterfaceType variableType,
String name,
Expression scope) {
String variableName = getNextVariableName();
final VariableDeclarationExpr toAdd = getVariableDeclaratorWithFieldAccessExpr(variableName,
variableType,
name,
scope);
return addExpression(toAdd, variableName);
}
private BlockStmt addExpression(Expression toAdd, String variableName) {
lastVariableName.set(variableName);
return addExpression(toAdd);
}
private BlockStmt addExpression(Expression toAdd) {
toPopulate.addStatement(toAdd);
LOGGER.debug(toPopulate.toString());
return toPopulate;
}
private BlockStmt addStatement(Statement toAdd) {
toPopulate.addStatement(toAdd);
LOGGER.debug(toPopulate.toString());
return toPopulate;
}
private Expression getTypeExpression(Type type) {
if (!typeCache.containsKey(type)) {
Expression toPut;
if (type instanceof AliasFEELType aliasFEELType) {
toPut = getAliasFEELType(aliasFEELType);
} else if (type instanceof Enum typeEnum) {
toPut = getEnumExpression(typeEnum);
} else if (type instanceof JavaBackedType javaBackedType) {
toPut = getJavaBackedTypeExpression(javaBackedType);
} else if (type instanceof MapBackedType mapBackedType) {
toPut = getMapBackedTypeExpression(mapBackedType);
} else {
toPut = parseExpression(type.getClass().getCanonicalName());
}
typeCache.put(type, toPut);
}
return typeCache.get(type);
}
private Expression getAliasFEELType(AliasFEELType aliasFEELType) {
BuiltInType feelCType = aliasFEELType.getBuiltInType();
Expression typeExpression = new FieldAccessExpr(BUILTINTYPE_E, feelCType.name());
// Creating the AliasFEELType
String aliasFeelTypeVariableName = getNextVariableName();
final VariableDeclarator aliasFeelTypeVariableDeclarator =
new VariableDeclarator(ALIASFEELTYPE_CT, aliasFeelTypeVariableName);
NodeList<Expression> arguments = NodeList.nodeList(new StringLiteralExpr(aliasFEELType.getName()),
typeExpression);
final ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr(null, ALIASFEELTYPE_CT,
arguments);
aliasFeelTypeVariableDeclarator.setInitializer(objectCreationExpr);
VariableDeclarationExpr mapVariableDeclarationExpr =
new VariableDeclarationExpr(aliasFeelTypeVariableDeclarator);
addExpression(mapVariableDeclarationExpr, aliasFeelTypeVariableName);
return new NameExpr(aliasFeelTypeVariableName);
}
private Expression getJavaBackedTypeExpression(JavaBackedType javaBackedType) {
// Creating the JavaBackedType
String mapVariableName = getNextVariableName();
final VariableDeclarator mapVariableDeclarator =
new VariableDeclarator(TYPE_CT, mapVariableName);
Expression classExpression = new NameExpr(javaBackedType.getWrapped().getCanonicalName() + ".class");
final MethodCallExpr methodCallExpr = new MethodCallExpr(JAVABACKEDTYPE_N, OF_S,
NodeList.nodeList(classExpression));
mapVariableDeclarator.setInitializer(methodCallExpr);
VariableDeclarationExpr mapVariableDeclarationExpr = new VariableDeclarationExpr(mapVariableDeclarator);
addExpression(mapVariableDeclarationExpr, mapVariableName);
return new NameExpr(mapVariableName);
}
private Expression getMapBackedTypeExpression(MapBackedType mapBackedType) {
Map<Expression, Expression> fieldsExpressions = new HashMap<>(); // The key is the StringLiteralExpr of the
// original key; the value is the Expression pointing at type
for (Map.Entry<String, Type> kv : mapBackedType.getFields().entrySet()) {
fieldsExpressions.put(new StringLiteralExpr(kv.getKey()), getTypeExpression(kv.getValue()));
}
// Creating the MapBackedType
String mapVariableName = getNextVariableName();
final VariableDeclarator mapVariableDeclarator =
new VariableDeclarator(MAPBACKEDTYPE_CT, mapVariableName);
final ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr(null, MAPBACKEDTYPE_CT,
NodeList.nodeList(new StringLiteralExpr(mapBackedType.getName())));
mapVariableDeclarator.setInitializer(objectCreationExpr);
VariableDeclarationExpr mapVariableDeclarationExpr = new VariableDeclarationExpr(mapVariableDeclarator);
addExpression(mapVariableDeclarationExpr, mapVariableName);
// Populating the map
Expression mapVariableExpression = new NameExpr(mapVariableName);
fieldsExpressions.forEach((key, value) -> {
MethodCallExpr putExpression = new MethodCallExpr(mapVariableExpression, ADDFIELD_S);
putExpression.addArgument(key);
putExpression.addArgument(value);
addExpression(putExpression);
});
return new NameExpr(mapVariableName);
}
private Expression getObjectExpression(Object object) {
if (object == null) {
return new NullLiteralExpr();
}
if (!objectCache.containsKey(object)) {
String variableName = getNextVariableName();
Expression objectExpression = CodegenUtils.getObjectExpression(object, variableName);
addExpression(objectExpression, variableName);
objectCache.put(object, new NameExpr(lastVariableName.get()));
}
return objectCache.get(object);
}
private Expression getNodeExpression(BaseNode node) {
if (node != null) {
if (!baseNodeCache.containsKey(node)) {
node.accept(astCompilerVisitor);
baseNodeCache.put(node, new NameExpr(lastVariableName.get()));
}
return baseNodeCache.get(node);
} else {
return new NullLiteralExpr();
}
}
} |
apache/kylin | 35,764 | src/query/src/test/java/org/apache/kylin/query/security/HackSelectStarWithColumnACLTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.query.security;
import static org.apache.kylin.common.util.TestUtils.getTestConfig;
import java.util.Arrays;
import java.util.List;
import org.apache.kylin.common.QueryContext;
import org.apache.kylin.guava30.shaded.common.collect.Lists;
import org.apache.kylin.guava30.shaded.common.collect.Sets;
import org.apache.kylin.junit.annotation.MetadataInfo;
import org.apache.kylin.junit.annotation.OverwriteProp;
import org.apache.kylin.metadata.acl.AclTCR;
import org.apache.kylin.metadata.acl.AclTCRManager;
import org.apache.kylin.metadata.model.ColumnDesc;
import org.apache.kylin.metadata.model.NTableMetadataManager;
import org.apache.kylin.metadata.model.TableDesc;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@MetadataInfo
@OverwriteProp(value = "false", key = "kylin.pushdown.select-star-case-sensitive-enabled")
class HackSelectStarWithColumnACLTest {
private static final String PROJECT = "default";
private static final String SCHEMA = "DEFAULT";
private static final HackSelectStarWithColumnACL TRANSFORMER = new HackSelectStarWithColumnACL();
QueryContext current = QueryContext.current();
@BeforeEach
void setup() {
getTestConfig().setProperty("kylin.query.security.acl-tcr-enabled", "true");
prepareBasic();
current.setAclInfo(new QueryContext.AclInfo("u1", Sets.newHashSet("g1"), false));
}
@AfterAll
static void afterAll() {
QueryContext.current().close();
}
@Test
void testJoin() {
// without alias
{
String sql = "select * from TEST_KYLIN_FACT join TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with alias
{
String sql = "select * from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with alias without select star
{
String sql = "select t1.ORDER_ID from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select t1.ORDER_ID from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with tow alias
{
String sql = "select * from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID"
+ " join TEST_ORDER t3 on t1.ORDER_ID = t3.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T3\" "
+ "on t1.ORDER_ID = t3.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with tow alias without select star
{
String sql = "select t1.ORDER_ID from TEST_KYLIN_FACT t1 join TEST_ORDER t2 on t1.ORDER_ID = t2.ORDER_ID"
+ " join TEST_ORDER t3 on t1.ORDER_ID = t3.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select t1.ORDER_ID from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"T1\" "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T2\" "
+ "on t1.ORDER_ID = t2.ORDER_ID "
+ "join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"T3\" "
+ "on t1.ORDER_ID = t3.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// nested select star
{
String sql = "select * from (select * from TEST_KYLIN_FACT) t1 join TEST_ORDER t2 "
+ "on t1.ORDER_ID = t2.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from (" //
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\""
+ ") t1 join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\""
+ ") as \"T2\" on t1.ORDER_ID = t2.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testWithSubQuery() {
// simple case
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join \"TEST_ORDER\" on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// with-item has alias in with-body
{
String sql = "with \"TEMP_DEPT\" as (select fpd.order_id, fpd.buyer_id "
+ "from test_order as fpd group by fpd.order_id, fpd.buyer_id)\n"
+ "select fpd.order_id, fpd.buyer_id from temp_dept as fpd";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with \"TEMP_DEPT\" as (select fpd.order_id, fpd.buyer_id from ( "
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", \"TEST_ORDER\".\"TEST_DATE_ENC\" "
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"FPD\" group by fpd.order_id, fpd.buyer_id)\n"
+ "select fpd.order_id, fpd.buyer_id from \"TEMP_DEPT\" as \"FPD\"";
Assertions.assertEquals(expected, converted);
}
// some content of with-body reuse with-items
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "join (select * from \"TEST_ORDER\") TEST_ORDER on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// all contexts of with-body do not reuse any with-items
{
String sql = "with test_order as (select * from test_order)\n"
+ "select * from TEST_KYLIN_FACT join (select * from \"DEFAULT\".\"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (select * from ( "
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")\n"
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" " //
+ "join (select * from ( " //
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" "
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
// all contexts of with-body reuse with-items
{
String sql = "with test_order as (select * from test_order), "
+ "test_kylin_fact as (select * from test_kylin_fact)\n"
+ "select * from TEST_KYLIN_FACT join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "with test_order as (" //
+ "select * from ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"), " //
+ "test_kylin_fact as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")\n"
+ "select * from \"TEST_KYLIN_FACT\" join (select * from \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT.ORDER_ID = TEST_ORDER.ORDER_ID";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testResolvedSorted() {
{
String sql = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from TEST_ORDER ) as o2" //
+ " from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from " //
+ "( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" ) as o2" //
+ " from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
{
String sql = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from TEST_KYLIN_FACT ) as o2" //
+ " from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select " //
+ " sum(ORDER_ID)," //
+ " (select sum(ORDER_ID) from " //
+ "( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" ) as o2" //
+ " from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testWithoutSubQueryFrom() {
// without from
{
String sql = "select -((select sum(ORDER_ID) from test_kylin_fact)"
+ " -(select sum(ORDER_ID) from test_kylin_fact)" //
+ ") as a1";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ " -(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlIdentifier in selectList
{
String sql = "select -((select sum(ORDER_ID) from test_kylin_fact)"
+ " -(select sum(ORDER_ID) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ " -(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlWith in selectList
{
String sql = "select -((" //
+ "with test_kylin_fact1 as (select * from test_kylin_fact) "
+ "select sum(ORDER_ID) from test_kylin_fact1)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "with test_kylin_fact1 as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") " //
+ "select sum(ORDER_ID) from \"TEST_KYLIN_FACT1\")" //
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
{
String sql = "select -((" //
+ "with test_order as (select * from test_order), "
+ "test_kylin_fact1 as (select * from test_kylin_fact) "
+ "select sum(TEST_KYLIN_FACT1.ORDER_ID) from TEST_KYLIN_FACT1"
+ " join (select * from TEST_ORDER) TEST_ORDER "
+ "on TEST_KYLIN_FACT1.ORDER_ID = TEST_ORDER.ORDER_ID limit 1)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "with test_order as (" //
+ "select * from ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" " //
+ "from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"), " //
+ "test_kylin_fact1 as ("
+ "select * from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") "
+ "select sum(TEST_KYLIN_FACT1.ORDER_ID) from \"TEST_KYLIN_FACT1\""
+ " join (select * from \"TEST_ORDER\") TEST_ORDER "
+ "on TEST_KYLIN_FACT1.ORDER_ID = TEST_ORDER.ORDER_ID limit 1)" //
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from and with SqlJoin in selectList
{
String sql = "select -((" //
+ "select sum(t1.ORDER_ID) from (select * from TEST_KYLIN_FACT) t1 join TEST_ORDER t2 "
+ "on t1.ORDER_ID = t2.ORDER_ID)" //
+ " -(select sum(PRICE) from test_kylin_fact)" //
+ ") as a1, sum(ORDER_ID) as a2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select -((" //
+ "select sum(t1.ORDER_ID) from (" //
+ "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\""
+ ") t1 join ( select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\""
+ ") as \"T2\" on t1.ORDER_ID = t2.ORDER_ID)"//
+ " -(select sum(PRICE) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ") as a1, sum(ORDER_ID) as a2";
Assertions.assertEquals(expected, converted);
}
// without from with null
{
String sql = "select (select sum(ORDER_ID), null from test_kylin_fact)"
+ ",(select sum(ORDER_ID) from test_kylin_fact) as a1";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select (select sum(ORDER_ID), null from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\")" //
+ ",(select sum(ORDER_ID) from" //
+ " ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\") as a1";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testUnion() {
// without outer select
{
String sql = "select * from test_order union select * from test_order";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "union select * from ( " //
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\"";
Assertions.assertEquals(expected, converted);
}
// with outer select
{
String sql = "select * from (select * from test_order union select * from test_order)";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from (select * from ( " //
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\" "
+ "union select * from ( " //
+ "select \"TEST_ORDER\".\"ORDER_ID\", \"TEST_ORDER\".\"BUYER_ID\", "
+ "\"TEST_ORDER\".\"TEST_DATE_ENC\" from \"DEFAULT\".\"TEST_ORDER\") as \"TEST_ORDER\")";
Assertions.assertEquals(expected, converted);
}
}
@Test
void testInSubQuery() {
String sql = "select * from TEST_KYLIN_FACT "
+ "where ITEM_COUNT in (select ITEM_COUNT from (select * from TEST_KYLIN_FACT) )";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "where ITEM_COUNT in (select ITEM_COUNT from (select * from TEST_KYLIN_FACT) )";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
@Test
void testCaseWhen() {
{
String sql = "select (case when ITEM_COUNT > 0 " //
+ "then (case when order_id > 0 then order_id else 1 end) " //
+ "else null end)\n" //
+ "from TEST_KYLIN_FACT";
String expected = "select (case when ITEM_COUNT > 0 " //
+ "then (case when order_id > 0 then order_id else 1 end) " //
+ "else null end)\n" //
+ "from ( select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", " //
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
{
String sql = "select * from test_kylin_fact " //
+ "where case when ITEM_COUNT > 10 then item_count else 0 end";
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", " //
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" "
+ "where case when ITEM_COUNT > 10 then item_count else 0 end";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
}
@Test
void testSingleTable() {
// without limit
{
String sql = "select * from \"DEFAULT\".\"TEST_KYLIN_FACT\"";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// with alias
{
String sql = "select * from test_kylin_fact as test_kylin_fact";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// with limit-offset
{
String sql = "select * from test_kylin_fact as test_kylin_fact limit 10 offset 2";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\" limit 10 offset 2";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// agg
{
String sql = "select count(*) from \"DEFAULT\".\"TEST_KYLIN_FACT\"";
String expected = "select count(*) from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
// quoted lower case table name
{
String sql = "select * from \"default\".\"test_kylin_fact\"";
String expected = "select * from ( "
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"test_kylin_fact\"";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
Assertions.assertEquals(expected, converted);
}
}
@Test
void testKeywordAsColName() {
prepareMore();
NTableMetadataManager tableMetadataManager = NTableMetadataManager.getInstance(getTestConfig(), PROJECT);
TableDesc tableDesc = tableMetadataManager.getTableDesc("DEFAULT.TEST_KYLIN_FACT");
ColumnDesc[] columns = tableDesc.getColumns();
ColumnDesc colStartsWithNumber = new ColumnDesc(columns[0]);
colStartsWithNumber.setId("13");
colStartsWithNumber.setDatatype("date");
colStartsWithNumber.setName("2D");
ColumnDesc colWithKeyword = new ColumnDesc(columns[0]);
colWithKeyword.setId("14");
colWithKeyword.setDatatype("date");
colWithKeyword.setName("YEAR");
List<ColumnDesc> columnDescs = Lists.newArrayList(columns);
columnDescs.add(colStartsWithNumber);
columnDescs.add(colWithKeyword);
tableDesc.setColumns(columnDescs.toArray(new ColumnDesc[0]));
tableMetadataManager.updateTableDesc(tableDesc);
String sql = "select * from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", \"TEST_KYLIN_FACT\".\"PRICE\", "
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\", \"TEST_KYLIN_FACT\".\"2D\", \"TEST_KYLIN_FACT\".\"YEAR\" "
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
@Test
void testColumnNameStartsWithNumber() {
prepareMore();
NTableMetadataManager tableMetadataManager = NTableMetadataManager.getInstance(getTestConfig(), PROJECT);
TableDesc tableDesc = tableMetadataManager.getTableDesc("DEFAULT.TEST_KYLIN_FACT");
ColumnDesc[] columns = tableDesc.getColumns();
ColumnDesc colStartsWithNumber = new ColumnDesc(columns[0]);
colStartsWithNumber.setId("13");
colStartsWithNumber.setDatatype("date");
colStartsWithNumber.setName("2D");
ColumnDesc colWithKeyword = new ColumnDesc(columns[0]);
colWithKeyword.setId("14");
colWithKeyword.setDatatype("date");
colWithKeyword.setName("YEAR");
List<ColumnDesc> columnDescs = Lists.newArrayList(columns);
columnDescs.add(colStartsWithNumber);
columnDescs.add(colWithKeyword);
tableDesc.setColumns(columnDescs.toArray(new ColumnDesc[0]));
tableMetadataManager.updateTableDesc(tableDesc);
String sql = "select * from TEST_KYLIN_FACT";
String converted = TRANSFORMER.convert(sql, PROJECT, SCHEMA);
String expected = "select * from ( " //
+ "select \"TEST_KYLIN_FACT\".\"ORDER_ID\", " //
+ "\"TEST_KYLIN_FACT\".\"PRICE\", " //
+ "\"TEST_KYLIN_FACT\".\"ITEM_COUNT\", " //
+ "\"TEST_KYLIN_FACT\".\"2D\", " //
+ "\"TEST_KYLIN_FACT\".\"YEAR\" " //
+ "from \"DEFAULT\".\"TEST_KYLIN_FACT\") as \"TEST_KYLIN_FACT\"";
Assertions.assertEquals(expected, converted);
}
@Test
void testExplainSyntax() {
String sql = "explain plan for select * from t";
Assertions.assertEquals(sql, TRANSFORMER.convert("explain plan for select * from t", PROJECT, SCHEMA));
}
private void prepareMore() {
AclTCRManager manager = AclTCRManager.getInstance(getTestConfig(), PROJECT);
AclTCR g1a1 = new AclTCR();
AclTCR.Table g1t1 = new AclTCR.Table();
AclTCR.ColumnRow g1cr1 = new AclTCR.ColumnRow();
AclTCR.Column g1c1 = new AclTCR.Column();
g1c1.addAll(Arrays.asList("ORDER_ID", "2D", "YEAR"));
g1cr1.setColumn(g1c1);
g1t1.put("DEFAULT.TEST_KYLIN_FACT", g1cr1);
g1a1.setTable(g1t1);
manager.updateAclTCR(g1a1, "g1", false);
}
private void prepareBasic() {
AclTCRManager manager = AclTCRManager.getInstance(getTestConfig(), PROJECT);
AclTCR u1a1 = new AclTCR();
AclTCR.Table u1t1 = new AclTCR.Table();
AclTCR.ColumnRow u1cr1 = new AclTCR.ColumnRow();
AclTCR.Column u1c1 = new AclTCR.Column();
u1c1.addAll(Arrays.asList("PRICE", "ITEM_COUNT"));
u1cr1.setColumn(u1c1);
AclTCR.ColumnRow u1cr2 = new AclTCR.ColumnRow();
AclTCR.Column u1c2 = new AclTCR.Column();
u1c2.addAll(Arrays.asList("ORDER_ID", "BUYER_ID", "TEST_DATE_ENC"));
u1cr2.setColumn(u1c2);
u1t1.put("DEFAULT.TEST_KYLIN_FACT", u1cr1);
u1t1.put("DEFAULT.TEST_ORDER", u1cr2);
u1a1.setTable(u1t1);
manager.updateAclTCR(u1a1, "u1", true);
AclTCR g1a1 = new AclTCR();
AclTCR.Table g1t1 = new AclTCR.Table();
AclTCR.ColumnRow g1cr1 = new AclTCR.ColumnRow();
AclTCR.Column g1c1 = new AclTCR.Column();
g1c1.add("ORDER_ID");
g1cr1.setColumn(g1c1);
g1t1.put("DEFAULT.TEST_KYLIN_FACT", g1cr1);
g1a1.setTable(g1t1);
manager.updateAclTCR(g1a1, "g1", false);
}
}
|
googleapis/google-cloud-java | 38,017 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SetIamPolicyMachineImageRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for MachineImages.SetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SetIamPolicyMachineImageRequest}
*/
public final class SetIamPolicyMachineImageRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SetIamPolicyMachineImageRequest)
SetIamPolicyMachineImageRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use SetIamPolicyMachineImageRequest.newBuilder() to construct.
private SetIamPolicyMachineImageRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SetIamPolicyMachineImageRequest() {
project_ = "";
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SetIamPolicyMachineImageRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetIamPolicyMachineImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetIamPolicyMachineImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.class,
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.Builder.class);
}
private int bitField0_;
public static final int GLOBAL_SET_POLICY_REQUEST_RESOURCE_FIELD_NUMBER = 337048498;
private com.google.cloud.compute.v1.GlobalSetPolicyRequest globalSetPolicyRequestResource_;
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the globalSetPolicyRequestResource field is set.
*/
@java.lang.Override
public boolean hasGlobalSetPolicyRequestResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The globalSetPolicyRequestResource.
*/
@java.lang.Override
public com.google.cloud.compute.v1.GlobalSetPolicyRequest getGlobalSetPolicyRequestResource() {
return globalSetPolicyRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()
: globalSetPolicyRequestResource_;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder
getGlobalSetPolicyRequestResourceOrBuilder() {
return globalSetPolicyRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()
: globalSetPolicyRequestResource_;
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_FIELD_NUMBER = 195806222;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(337048498, getGlobalSetPolicyRequestResource());
}
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(195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
337048498, getGlobalSetPolicyRequestResource());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest other =
(com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest) obj;
if (hasGlobalSetPolicyRequestResource() != other.hasGlobalSetPolicyRequestResource())
return false;
if (hasGlobalSetPolicyRequestResource()) {
if (!getGlobalSetPolicyRequestResource().equals(other.getGlobalSetPolicyRequestResource()))
return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getResource().equals(other.getResource())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasGlobalSetPolicyRequestResource()) {
hash = (37 * hash) + GLOBAL_SET_POLICY_REQUEST_RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGlobalSetPolicyRequestResource().hashCode();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest 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 MachineImages.SetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SetIamPolicyMachineImageRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SetIamPolicyMachineImageRequest)
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetIamPolicyMachineImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetIamPolicyMachineImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.class,
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getGlobalSetPolicyRequestResourceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
globalSetPolicyRequestResource_ = null;
if (globalSetPolicyRequestResourceBuilder_ != null) {
globalSetPolicyRequestResourceBuilder_.dispose();
globalSetPolicyRequestResourceBuilder_ = null;
}
project_ = "";
resource_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetIamPolicyMachineImageRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest build() {
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest buildPartial() {
com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest result =
new com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.globalSetPolicyRequestResource_ =
globalSetPolicyRequestResourceBuilder_ == null
? globalSetPolicyRequestResource_
: globalSetPolicyRequestResourceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.resource_ = resource_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest) {
return mergeFrom((com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest other) {
if (other == com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest.getDefaultInstance())
return this;
if (other.hasGlobalSetPolicyRequestResource()) {
mergeGlobalSetPolicyRequestResource(other.getGlobalSetPolicyRequestResource());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
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 1566449778:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1566449778
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -1598579310:
{
input.readMessage(
getGlobalSetPolicyRequestResourceFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case -1598579310
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.compute.v1.GlobalSetPolicyRequest globalSetPolicyRequestResource_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetPolicyRequest,
com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder,
com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder>
globalSetPolicyRequestResourceBuilder_;
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the globalSetPolicyRequestResource field is set.
*/
public boolean hasGlobalSetPolicyRequestResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The globalSetPolicyRequestResource.
*/
public com.google.cloud.compute.v1.GlobalSetPolicyRequest getGlobalSetPolicyRequestResource() {
if (globalSetPolicyRequestResourceBuilder_ == null) {
return globalSetPolicyRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()
: globalSetPolicyRequestResource_;
} else {
return globalSetPolicyRequestResourceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGlobalSetPolicyRequestResource(
com.google.cloud.compute.v1.GlobalSetPolicyRequest value) {
if (globalSetPolicyRequestResourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
globalSetPolicyRequestResource_ = value;
} else {
globalSetPolicyRequestResourceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGlobalSetPolicyRequestResource(
com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder builderForValue) {
if (globalSetPolicyRequestResourceBuilder_ == null) {
globalSetPolicyRequestResource_ = builderForValue.build();
} else {
globalSetPolicyRequestResourceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeGlobalSetPolicyRequestResource(
com.google.cloud.compute.v1.GlobalSetPolicyRequest value) {
if (globalSetPolicyRequestResourceBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& globalSetPolicyRequestResource_ != null
&& globalSetPolicyRequestResource_
!= com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()) {
getGlobalSetPolicyRequestResourceBuilder().mergeFrom(value);
} else {
globalSetPolicyRequestResource_ = value;
}
} else {
globalSetPolicyRequestResourceBuilder_.mergeFrom(value);
}
if (globalSetPolicyRequestResource_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearGlobalSetPolicyRequestResource() {
bitField0_ = (bitField0_ & ~0x00000001);
globalSetPolicyRequestResource_ = null;
if (globalSetPolicyRequestResourceBuilder_ != null) {
globalSetPolicyRequestResourceBuilder_.dispose();
globalSetPolicyRequestResourceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder
getGlobalSetPolicyRequestResourceBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getGlobalSetPolicyRequestResourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder
getGlobalSetPolicyRequestResourceOrBuilder() {
if (globalSetPolicyRequestResourceBuilder_ != null) {
return globalSetPolicyRequestResourceBuilder_.getMessageOrBuilder();
} else {
return globalSetPolicyRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()
: globalSetPolicyRequestResource_;
}
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetPolicyRequest,
com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder,
com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder>
getGlobalSetPolicyRequestResourceFieldBuilder() {
if (globalSetPolicyRequestResourceBuilder_ == null) {
globalSetPolicyRequestResourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetPolicyRequest,
com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder,
com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder>(
getGlobalSetPolicyRequestResource(), getParentForChildren(), isClean());
globalSetPolicyRequestResource_ = null;
}
return globalSetPolicyRequestResourceBuilder_;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.SetIamPolicyMachineImageRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SetIamPolicyMachineImageRequest)
private static final com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest();
}
public static com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SetIamPolicyMachineImageRequest> PARSER =
new com.google.protobuf.AbstractParser<SetIamPolicyMachineImageRequest>() {
@java.lang.Override
public SetIamPolicyMachineImageRequest 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<SetIamPolicyMachineImageRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SetIamPolicyMachineImageRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetIamPolicyMachineImageRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,975 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/SampleConfig.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/data_labeling_job.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Active learning data sampling config. For every active learning labeling
* iteration, it will select a batch of data based on the sampling strategy.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SampleConfig}
*/
public final class SampleConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.SampleConfig)
SampleConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use SampleConfig.newBuilder() to construct.
private SampleConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SampleConfig() {
sampleStrategy_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SampleConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.DataLabelingJobProto
.internal_static_google_cloud_aiplatform_v1beta1_SampleConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.DataLabelingJobProto
.internal_static_google_cloud_aiplatform_v1beta1_SampleConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SampleConfig.class,
com.google.cloud.aiplatform.v1beta1.SampleConfig.Builder.class);
}
/**
*
*
* <pre>
* Sample strategy decides which subset of DataItems should be selected for
* human labeling in every batch.
* </pre>
*
* Protobuf enum {@code google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy}
*/
public enum SampleStrategy implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Default will be treated as UNCERTAINTY.
* </pre>
*
* <code>SAMPLE_STRATEGY_UNSPECIFIED = 0;</code>
*/
SAMPLE_STRATEGY_UNSPECIFIED(0),
/**
*
*
* <pre>
* Sample the most uncertain data to label.
* </pre>
*
* <code>UNCERTAINTY = 1;</code>
*/
UNCERTAINTY(1),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Default will be treated as UNCERTAINTY.
* </pre>
*
* <code>SAMPLE_STRATEGY_UNSPECIFIED = 0;</code>
*/
public static final int SAMPLE_STRATEGY_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* Sample the most uncertain data to label.
* </pre>
*
* <code>UNCERTAINTY = 1;</code>
*/
public static final int UNCERTAINTY_VALUE = 1;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SampleStrategy valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static SampleStrategy forNumber(int value) {
switch (value) {
case 0:
return SAMPLE_STRATEGY_UNSPECIFIED;
case 1:
return UNCERTAINTY;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<SampleStrategy> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<SampleStrategy> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<SampleStrategy>() {
public SampleStrategy findValueByNumber(int number) {
return SampleStrategy.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.SampleConfig.getDescriptor().getEnumTypes().get(0);
}
private static final SampleStrategy[] VALUES = values();
public static SampleStrategy valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private SampleStrategy(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy)
}
private int initialBatchSampleSizeCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object initialBatchSampleSize_;
public enum InitialBatchSampleSizeCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
INITIAL_BATCH_SAMPLE_PERCENTAGE(1),
INITIALBATCHSAMPLESIZE_NOT_SET(0);
private final int value;
private InitialBatchSampleSizeCase(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 InitialBatchSampleSizeCase valueOf(int value) {
return forNumber(value);
}
public static InitialBatchSampleSizeCase forNumber(int value) {
switch (value) {
case 1:
return INITIAL_BATCH_SAMPLE_PERCENTAGE;
case 0:
return INITIALBATCHSAMPLESIZE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public InitialBatchSampleSizeCase getInitialBatchSampleSizeCase() {
return InitialBatchSampleSizeCase.forNumber(initialBatchSampleSizeCase_);
}
private int followingBatchSampleSizeCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object followingBatchSampleSize_;
public enum FollowingBatchSampleSizeCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
FOLLOWING_BATCH_SAMPLE_PERCENTAGE(3),
FOLLOWINGBATCHSAMPLESIZE_NOT_SET(0);
private final int value;
private FollowingBatchSampleSizeCase(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 FollowingBatchSampleSizeCase valueOf(int value) {
return forNumber(value);
}
public static FollowingBatchSampleSizeCase forNumber(int value) {
switch (value) {
case 3:
return FOLLOWING_BATCH_SAMPLE_PERCENTAGE;
case 0:
return FOLLOWINGBATCHSAMPLESIZE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public FollowingBatchSampleSizeCase getFollowingBatchSampleSizeCase() {
return FollowingBatchSampleSizeCase.forNumber(followingBatchSampleSizeCase_);
}
public static final int INITIAL_BATCH_SAMPLE_PERCENTAGE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @return Whether the initialBatchSamplePercentage field is set.
*/
@java.lang.Override
public boolean hasInitialBatchSamplePercentage() {
return initialBatchSampleSizeCase_ == 1;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @return The initialBatchSamplePercentage.
*/
@java.lang.Override
public int getInitialBatchSamplePercentage() {
if (initialBatchSampleSizeCase_ == 1) {
return (java.lang.Integer) initialBatchSampleSize_;
}
return 0;
}
public static final int FOLLOWING_BATCH_SAMPLE_PERCENTAGE_FIELD_NUMBER = 3;
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @return Whether the followingBatchSamplePercentage field is set.
*/
@java.lang.Override
public boolean hasFollowingBatchSamplePercentage() {
return followingBatchSampleSizeCase_ == 3;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @return The followingBatchSamplePercentage.
*/
@java.lang.Override
public int getFollowingBatchSamplePercentage() {
if (followingBatchSampleSizeCase_ == 3) {
return (java.lang.Integer) followingBatchSampleSize_;
}
return 0;
}
public static final int SAMPLE_STRATEGY_FIELD_NUMBER = 5;
private int sampleStrategy_ = 0;
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;</code>
*
* @return The enum numeric value on the wire for sampleStrategy.
*/
@java.lang.Override
public int getSampleStrategyValue() {
return sampleStrategy_;
}
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;</code>
*
* @return The sampleStrategy.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy getSampleStrategy() {
com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy result =
com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy.forNumber(sampleStrategy_);
return result == null
? com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy.UNRECOGNIZED
: result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (initialBatchSampleSizeCase_ == 1) {
output.writeInt32(1, (int) ((java.lang.Integer) initialBatchSampleSize_));
}
if (followingBatchSampleSizeCase_ == 3) {
output.writeInt32(3, (int) ((java.lang.Integer) followingBatchSampleSize_));
}
if (sampleStrategy_
!= com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy
.SAMPLE_STRATEGY_UNSPECIFIED
.getNumber()) {
output.writeEnum(5, sampleStrategy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (initialBatchSampleSizeCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeInt32Size(
1, (int) ((java.lang.Integer) initialBatchSampleSize_));
}
if (followingBatchSampleSizeCase_ == 3) {
size +=
com.google.protobuf.CodedOutputStream.computeInt32Size(
3, (int) ((java.lang.Integer) followingBatchSampleSize_));
}
if (sampleStrategy_
!= com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy
.SAMPLE_STRATEGY_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(5, sampleStrategy_);
}
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.SampleConfig)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.SampleConfig other =
(com.google.cloud.aiplatform.v1beta1.SampleConfig) obj;
if (sampleStrategy_ != other.sampleStrategy_) return false;
if (!getInitialBatchSampleSizeCase().equals(other.getInitialBatchSampleSizeCase()))
return false;
switch (initialBatchSampleSizeCase_) {
case 1:
if (getInitialBatchSamplePercentage() != other.getInitialBatchSamplePercentage())
return false;
break;
case 0:
default:
}
if (!getFollowingBatchSampleSizeCase().equals(other.getFollowingBatchSampleSizeCase()))
return false;
switch (followingBatchSampleSizeCase_) {
case 3:
if (getFollowingBatchSamplePercentage() != other.getFollowingBatchSamplePercentage())
return false;
break;
case 0:
default:
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + SAMPLE_STRATEGY_FIELD_NUMBER;
hash = (53 * hash) + sampleStrategy_;
switch (initialBatchSampleSizeCase_) {
case 1:
hash = (37 * hash) + INITIAL_BATCH_SAMPLE_PERCENTAGE_FIELD_NUMBER;
hash = (53 * hash) + getInitialBatchSamplePercentage();
break;
case 0:
default:
}
switch (followingBatchSampleSizeCase_) {
case 3:
hash = (37 * hash) + FOLLOWING_BATCH_SAMPLE_PERCENTAGE_FIELD_NUMBER;
hash = (53 * hash) + getFollowingBatchSamplePercentage();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig 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.SampleConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig 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.SampleConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig 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.SampleConfig parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig 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.SampleConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig 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.SampleConfig 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.SampleConfig 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.SampleConfig 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>
* Active learning data sampling config. For every active learning labeling
* iteration, it will select a batch of data based on the sampling strategy.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SampleConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.SampleConfig)
com.google.cloud.aiplatform.v1beta1.SampleConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.DataLabelingJobProto
.internal_static_google_cloud_aiplatform_v1beta1_SampleConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.DataLabelingJobProto
.internal_static_google_cloud_aiplatform_v1beta1_SampleConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SampleConfig.class,
com.google.cloud.aiplatform.v1beta1.SampleConfig.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.SampleConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
sampleStrategy_ = 0;
initialBatchSampleSizeCase_ = 0;
initialBatchSampleSize_ = null;
followingBatchSampleSizeCase_ = 0;
followingBatchSampleSize_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.DataLabelingJobProto
.internal_static_google_cloud_aiplatform_v1beta1_SampleConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.SampleConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig build() {
com.google.cloud.aiplatform.v1beta1.SampleConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig buildPartial() {
com.google.cloud.aiplatform.v1beta1.SampleConfig result =
new com.google.cloud.aiplatform.v1beta1.SampleConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.SampleConfig result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.sampleStrategy_ = sampleStrategy_;
}
}
private void buildPartialOneofs(com.google.cloud.aiplatform.v1beta1.SampleConfig result) {
result.initialBatchSampleSizeCase_ = initialBatchSampleSizeCase_;
result.initialBatchSampleSize_ = this.initialBatchSampleSize_;
result.followingBatchSampleSizeCase_ = followingBatchSampleSizeCase_;
result.followingBatchSampleSize_ = this.followingBatchSampleSize_;
}
@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.SampleConfig) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.SampleConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.SampleConfig other) {
if (other == com.google.cloud.aiplatform.v1beta1.SampleConfig.getDefaultInstance())
return this;
if (other.sampleStrategy_ != 0) {
setSampleStrategyValue(other.getSampleStrategyValue());
}
switch (other.getInitialBatchSampleSizeCase()) {
case INITIAL_BATCH_SAMPLE_PERCENTAGE:
{
setInitialBatchSamplePercentage(other.getInitialBatchSamplePercentage());
break;
}
case INITIALBATCHSAMPLESIZE_NOT_SET:
{
break;
}
}
switch (other.getFollowingBatchSampleSizeCase()) {
case FOLLOWING_BATCH_SAMPLE_PERCENTAGE:
{
setFollowingBatchSamplePercentage(other.getFollowingBatchSamplePercentage());
break;
}
case FOLLOWINGBATCHSAMPLESIZE_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
initialBatchSampleSize_ = input.readInt32();
initialBatchSampleSizeCase_ = 1;
break;
} // case 8
case 24:
{
followingBatchSampleSize_ = input.readInt32();
followingBatchSampleSizeCase_ = 3;
break;
} // case 24
case 40:
{
sampleStrategy_ = input.readEnum();
bitField0_ |= 0x00000004;
break;
} // case 40
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 initialBatchSampleSizeCase_ = 0;
private java.lang.Object initialBatchSampleSize_;
public InitialBatchSampleSizeCase getInitialBatchSampleSizeCase() {
return InitialBatchSampleSizeCase.forNumber(initialBatchSampleSizeCase_);
}
public Builder clearInitialBatchSampleSize() {
initialBatchSampleSizeCase_ = 0;
initialBatchSampleSize_ = null;
onChanged();
return this;
}
private int followingBatchSampleSizeCase_ = 0;
private java.lang.Object followingBatchSampleSize_;
public FollowingBatchSampleSizeCase getFollowingBatchSampleSizeCase() {
return FollowingBatchSampleSizeCase.forNumber(followingBatchSampleSizeCase_);
}
public Builder clearFollowingBatchSampleSize() {
followingBatchSampleSizeCase_ = 0;
followingBatchSampleSize_ = null;
onChanged();
return this;
}
private int bitField0_;
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @return Whether the initialBatchSamplePercentage field is set.
*/
public boolean hasInitialBatchSamplePercentage() {
return initialBatchSampleSizeCase_ == 1;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @return The initialBatchSamplePercentage.
*/
public int getInitialBatchSamplePercentage() {
if (initialBatchSampleSizeCase_ == 1) {
return (java.lang.Integer) initialBatchSampleSize_;
}
return 0;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @param value The initialBatchSamplePercentage to set.
* @return This builder for chaining.
*/
public Builder setInitialBatchSamplePercentage(int value) {
initialBatchSampleSizeCase_ = 1;
initialBatchSampleSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in the first batch.
* </pre>
*
* <code>int32 initial_batch_sample_percentage = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearInitialBatchSamplePercentage() {
if (initialBatchSampleSizeCase_ == 1) {
initialBatchSampleSizeCase_ = 0;
initialBatchSampleSize_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @return Whether the followingBatchSamplePercentage field is set.
*/
public boolean hasFollowingBatchSamplePercentage() {
return followingBatchSampleSizeCase_ == 3;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @return The followingBatchSamplePercentage.
*/
public int getFollowingBatchSamplePercentage() {
if (followingBatchSampleSizeCase_ == 3) {
return (java.lang.Integer) followingBatchSampleSize_;
}
return 0;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @param value The followingBatchSamplePercentage to set.
* @return This builder for chaining.
*/
public Builder setFollowingBatchSamplePercentage(int value) {
followingBatchSampleSizeCase_ = 3;
followingBatchSampleSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The percentage of data needed to be labeled in each following batch
* (except the first batch).
* </pre>
*
* <code>int32 following_batch_sample_percentage = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearFollowingBatchSamplePercentage() {
if (followingBatchSampleSizeCase_ == 3) {
followingBatchSampleSizeCase_ = 0;
followingBatchSampleSize_ = null;
onChanged();
}
return this;
}
private int sampleStrategy_ = 0;
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;
* </code>
*
* @return The enum numeric value on the wire for sampleStrategy.
*/
@java.lang.Override
public int getSampleStrategyValue() {
return sampleStrategy_;
}
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;
* </code>
*
* @param value The enum numeric value on the wire for sampleStrategy to set.
* @return This builder for chaining.
*/
public Builder setSampleStrategyValue(int value) {
sampleStrategy_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;
* </code>
*
* @return The sampleStrategy.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy getSampleStrategy() {
com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy result =
com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy.forNumber(
sampleStrategy_);
return result == null
? com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;
* </code>
*
* @param value The sampleStrategy to set.
* @return This builder for chaining.
*/
public Builder setSampleStrategy(
com.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
sampleStrategy_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Field to choose sampling strategy. Sampling strategy will decide which data
* should be selected for human labeling in every batch.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.SampleConfig.SampleStrategy sample_strategy = 5;
* </code>
*
* @return This builder for chaining.
*/
public Builder clearSampleStrategy() {
bitField0_ = (bitField0_ & ~0x00000004);
sampleStrategy_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.SampleConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.SampleConfig)
private static final com.google.cloud.aiplatform.v1beta1.SampleConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.SampleConfig();
}
public static com.google.cloud.aiplatform.v1beta1.SampleConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SampleConfig> PARSER =
new com.google.protobuf.AbstractParser<SampleConfig>() {
@java.lang.Override
public SampleConfig 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<SampleConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SampleConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SampleConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,109 | java-iap/proto-google-cloud-iap-v1/src/main/java/com/google/cloud/iap/v1/GcipSettings.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/iap/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.iap.v1;
/**
*
*
* <pre>
* Allows customers to configure tenant IDs for a Cloud Identity Platform (GCIP)
* instance for each application.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.GcipSettings}
*/
public final class GcipSettings extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iap.v1.GcipSettings)
GcipSettingsOrBuilder {
private static final long serialVersionUID = 0L;
// Use GcipSettings.newBuilder() to construct.
private GcipSettings(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GcipSettings() {
tenantIds_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GcipSettings();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_GcipSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_GcipSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.GcipSettings.class,
com.google.cloud.iap.v1.GcipSettings.Builder.class);
}
private int bitField0_;
public static final int TENANT_IDS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList tenantIds_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the tenantIds.
*/
public com.google.protobuf.ProtocolStringList getTenantIdsList() {
return tenantIds_;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of tenantIds.
*/
public int getTenantIdsCount() {
return tenantIds_.size();
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The tenantIds at the given index.
*/
public java.lang.String getTenantIds(int index) {
return tenantIds_.get(index);
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the tenantIds at the given index.
*/
public com.google.protobuf.ByteString getTenantIdsBytes(int index) {
return tenantIds_.getByteString(index);
}
public static final int LOGIN_PAGE_URI_FIELD_NUMBER = 2;
private com.google.protobuf.StringValue loginPageUri_;
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*
* @return Whether the loginPageUri field is set.
*/
@java.lang.Override
public boolean hasLoginPageUri() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*
* @return The loginPageUri.
*/
@java.lang.Override
public com.google.protobuf.StringValue getLoginPageUri() {
return loginPageUri_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginPageUri_;
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.StringValueOrBuilder getLoginPageUriOrBuilder() {
return loginPageUri_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginPageUri_;
}
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 < tenantIds_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, tenantIds_.getRaw(i));
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getLoginPageUri());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < tenantIds_.size(); i++) {
dataSize += computeStringSizeNoTag(tenantIds_.getRaw(i));
}
size += dataSize;
size += 1 * getTenantIdsList().size();
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getLoginPageUri());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.iap.v1.GcipSettings)) {
return super.equals(obj);
}
com.google.cloud.iap.v1.GcipSettings other = (com.google.cloud.iap.v1.GcipSettings) obj;
if (!getTenantIdsList().equals(other.getTenantIdsList())) return false;
if (hasLoginPageUri() != other.hasLoginPageUri()) return false;
if (hasLoginPageUri()) {
if (!getLoginPageUri().equals(other.getLoginPageUri())) 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 (getTenantIdsCount() > 0) {
hash = (37 * hash) + TENANT_IDS_FIELD_NUMBER;
hash = (53 * hash) + getTenantIdsList().hashCode();
}
if (hasLoginPageUri()) {
hash = (37 * hash) + LOGIN_PAGE_URI_FIELD_NUMBER;
hash = (53 * hash) + getLoginPageUri().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.GcipSettings parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.GcipSettings parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.GcipSettings parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.iap.v1.GcipSettings 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>
* Allows customers to configure tenant IDs for a Cloud Identity Platform (GCIP)
* instance for each application.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.GcipSettings}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iap.v1.GcipSettings)
com.google.cloud.iap.v1.GcipSettingsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_GcipSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_GcipSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.GcipSettings.class,
com.google.cloud.iap.v1.GcipSettings.Builder.class);
}
// Construct using com.google.cloud.iap.v1.GcipSettings.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getLoginPageUriFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
tenantIds_ = com.google.protobuf.LazyStringArrayList.emptyList();
loginPageUri_ = null;
if (loginPageUriBuilder_ != null) {
loginPageUriBuilder_.dispose();
loginPageUriBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_GcipSettings_descriptor;
}
@java.lang.Override
public com.google.cloud.iap.v1.GcipSettings getDefaultInstanceForType() {
return com.google.cloud.iap.v1.GcipSettings.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iap.v1.GcipSettings build() {
com.google.cloud.iap.v1.GcipSettings result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iap.v1.GcipSettings buildPartial() {
com.google.cloud.iap.v1.GcipSettings result = new com.google.cloud.iap.v1.GcipSettings(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.iap.v1.GcipSettings result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
tenantIds_.makeImmutable();
result.tenantIds_ = tenantIds_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.loginPageUri_ =
loginPageUriBuilder_ == null ? loginPageUri_ : loginPageUriBuilder_.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.iap.v1.GcipSettings) {
return mergeFrom((com.google.cloud.iap.v1.GcipSettings) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iap.v1.GcipSettings other) {
if (other == com.google.cloud.iap.v1.GcipSettings.getDefaultInstance()) return this;
if (!other.tenantIds_.isEmpty()) {
if (tenantIds_.isEmpty()) {
tenantIds_ = other.tenantIds_;
bitField0_ |= 0x00000001;
} else {
ensureTenantIdsIsMutable();
tenantIds_.addAll(other.tenantIds_);
}
onChanged();
}
if (other.hasLoginPageUri()) {
mergeLoginPageUri(other.getLoginPageUri());
}
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();
ensureTenantIdsIsMutable();
tenantIds_.add(s);
break;
} // case 10
case 18:
{
input.readMessage(getLoginPageUriFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringArrayList tenantIds_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureTenantIdsIsMutable() {
if (!tenantIds_.isModifiable()) {
tenantIds_ = new com.google.protobuf.LazyStringArrayList(tenantIds_);
}
bitField0_ |= 0x00000001;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the tenantIds.
*/
public com.google.protobuf.ProtocolStringList getTenantIdsList() {
tenantIds_.makeImmutable();
return tenantIds_;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of tenantIds.
*/
public int getTenantIdsCount() {
return tenantIds_.size();
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The tenantIds at the given index.
*/
public java.lang.String getTenantIds(int index) {
return tenantIds_.get(index);
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the tenantIds at the given index.
*/
public com.google.protobuf.ByteString getTenantIdsBytes(int index) {
return tenantIds_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index to set the value at.
* @param value The tenantIds to set.
* @return This builder for chaining.
*/
public Builder setTenantIds(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTenantIdsIsMutable();
tenantIds_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The tenantIds to add.
* @return This builder for chaining.
*/
public Builder addTenantIds(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTenantIdsIsMutable();
tenantIds_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param values The tenantIds to add.
* @return This builder for chaining.
*/
public Builder addAllTenantIds(java.lang.Iterable<java.lang.String> values) {
ensureTenantIdsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tenantIds_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearTenantIds() {
tenantIds_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. GCIP tenant IDs that are linked to the IAP resource. `tenant_ids`
* could be a string beginning with a number character to indicate
* authenticating with GCIP tenant flow, or in the format of
* `_<ProjectNumber>` to indicate authenticating with GCIP agent flow. If
* agent flow is used, `tenant_ids` should only contain one single element,
* while for tenant flow, `tenant_ids` can contain multiple elements.
* </pre>
*
* <code>repeated string tenant_ids = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes of the tenantIds to add.
* @return This builder for chaining.
*/
public Builder addTenantIdsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureTenantIdsIsMutable();
tenantIds_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.protobuf.StringValue loginPageUri_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>
loginPageUriBuilder_;
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*
* @return Whether the loginPageUri field is set.
*/
public boolean hasLoginPageUri() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*
* @return The loginPageUri.
*/
public com.google.protobuf.StringValue getLoginPageUri() {
if (loginPageUriBuilder_ == null) {
return loginPageUri_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginPageUri_;
} else {
return loginPageUriBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public Builder setLoginPageUri(com.google.protobuf.StringValue value) {
if (loginPageUriBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
loginPageUri_ = value;
} else {
loginPageUriBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public Builder setLoginPageUri(com.google.protobuf.StringValue.Builder builderForValue) {
if (loginPageUriBuilder_ == null) {
loginPageUri_ = builderForValue.build();
} else {
loginPageUriBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public Builder mergeLoginPageUri(com.google.protobuf.StringValue value) {
if (loginPageUriBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& loginPageUri_ != null
&& loginPageUri_ != com.google.protobuf.StringValue.getDefaultInstance()) {
getLoginPageUriBuilder().mergeFrom(value);
} else {
loginPageUri_ = value;
}
} else {
loginPageUriBuilder_.mergeFrom(value);
}
if (loginPageUri_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public Builder clearLoginPageUri() {
bitField0_ = (bitField0_ & ~0x00000002);
loginPageUri_ = null;
if (loginPageUriBuilder_ != null) {
loginPageUriBuilder_.dispose();
loginPageUriBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public com.google.protobuf.StringValue.Builder getLoginPageUriBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getLoginPageUriFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
public com.google.protobuf.StringValueOrBuilder getLoginPageUriOrBuilder() {
if (loginPageUriBuilder_ != null) {
return loginPageUriBuilder_.getMessageOrBuilder();
} else {
return loginPageUri_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginPageUri_;
}
}
/**
*
*
* <pre>
* Login page URI associated with the GCIP tenants.
* Typically, all resources within the same project share the same login page,
* though it could be overridden at the sub resource level.
* </pre>
*
* <code>.google.protobuf.StringValue login_page_uri = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>
getLoginPageUriFieldBuilder() {
if (loginPageUriBuilder_ == null) {
loginPageUriBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>(
getLoginPageUri(), getParentForChildren(), isClean());
loginPageUri_ = null;
}
return loginPageUriBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.iap.v1.GcipSettings)
}
// @@protoc_insertion_point(class_scope:google.cloud.iap.v1.GcipSettings)
private static final com.google.cloud.iap.v1.GcipSettings DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iap.v1.GcipSettings();
}
public static com.google.cloud.iap.v1.GcipSettings getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GcipSettings> PARSER =
new com.google.protobuf.AbstractParser<GcipSettings>() {
@java.lang.Override
public GcipSettings 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<GcipSettings> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GcipSettings> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iap.v1.GcipSettings getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,159 | java-storagebatchoperations/grpc-google-cloud-storagebatchoperations-v1/src/main/java/com/google/cloud/storagebatchoperations/v1/StorageBatchOperationsGrpc.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.storagebatchoperations.v1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/storagebatchoperations/v1/storage_batch_operations.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class StorageBatchOperationsGrpc {
private StorageBatchOperationsGrpc() {}
public static final java.lang.String SERVICE_NAME =
"google.cloud.storagebatchoperations.v1.StorageBatchOperations";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.ListJobsRequest,
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
getListJobsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListJobs",
requestType = com.google.cloud.storagebatchoperations.v1.ListJobsRequest.class,
responseType = com.google.cloud.storagebatchoperations.v1.ListJobsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.ListJobsRequest,
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
getListJobsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.ListJobsRequest,
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
getListJobsMethod;
if ((getListJobsMethod = StorageBatchOperationsGrpc.getListJobsMethod) == null) {
synchronized (StorageBatchOperationsGrpc.class) {
if ((getListJobsMethod = StorageBatchOperationsGrpc.getListJobsMethod) == null) {
StorageBatchOperationsGrpc.getListJobsMethod =
getListJobsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.storagebatchoperations.v1.ListJobsRequest,
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListJobs"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.ListJobsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.ListJobsResponse
.getDefaultInstance()))
.setSchemaDescriptor(
new StorageBatchOperationsMethodDescriptorSupplier("ListJobs"))
.build();
}
}
}
return getListJobsMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.GetJobRequest,
com.google.cloud.storagebatchoperations.v1.Job>
getGetJobMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetJob",
requestType = com.google.cloud.storagebatchoperations.v1.GetJobRequest.class,
responseType = com.google.cloud.storagebatchoperations.v1.Job.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.GetJobRequest,
com.google.cloud.storagebatchoperations.v1.Job>
getGetJobMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.GetJobRequest,
com.google.cloud.storagebatchoperations.v1.Job>
getGetJobMethod;
if ((getGetJobMethod = StorageBatchOperationsGrpc.getGetJobMethod) == null) {
synchronized (StorageBatchOperationsGrpc.class) {
if ((getGetJobMethod = StorageBatchOperationsGrpc.getGetJobMethod) == null) {
StorageBatchOperationsGrpc.getGetJobMethod =
getGetJobMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.storagebatchoperations.v1.GetJobRequest,
com.google.cloud.storagebatchoperations.v1.Job>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetJob"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.GetJobRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.Job.getDefaultInstance()))
.setSchemaDescriptor(
new StorageBatchOperationsMethodDescriptorSupplier("GetJob"))
.build();
}
}
}
return getGetJobMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CreateJobRequest,
com.google.longrunning.Operation>
getCreateJobMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateJob",
requestType = com.google.cloud.storagebatchoperations.v1.CreateJobRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CreateJobRequest,
com.google.longrunning.Operation>
getCreateJobMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CreateJobRequest,
com.google.longrunning.Operation>
getCreateJobMethod;
if ((getCreateJobMethod = StorageBatchOperationsGrpc.getCreateJobMethod) == null) {
synchronized (StorageBatchOperationsGrpc.class) {
if ((getCreateJobMethod = StorageBatchOperationsGrpc.getCreateJobMethod) == null) {
StorageBatchOperationsGrpc.getCreateJobMethod =
getCreateJobMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.storagebatchoperations.v1.CreateJobRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateJob"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.CreateJobRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(
new StorageBatchOperationsMethodDescriptorSupplier("CreateJob"))
.build();
}
}
}
return getCreateJobMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest, com.google.protobuf.Empty>
getDeleteJobMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteJob",
requestType = com.google.cloud.storagebatchoperations.v1.DeleteJobRequest.class,
responseType = com.google.protobuf.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest, com.google.protobuf.Empty>
getDeleteJobMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest, com.google.protobuf.Empty>
getDeleteJobMethod;
if ((getDeleteJobMethod = StorageBatchOperationsGrpc.getDeleteJobMethod) == null) {
synchronized (StorageBatchOperationsGrpc.class) {
if ((getDeleteJobMethod = StorageBatchOperationsGrpc.getDeleteJobMethod) == null) {
StorageBatchOperationsGrpc.getDeleteJobMethod =
getDeleteJobMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.storagebatchoperations.v1.DeleteJobRequest,
com.google.protobuf.Empty>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteJob"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.protobuf.Empty.getDefaultInstance()))
.setSchemaDescriptor(
new StorageBatchOperationsMethodDescriptorSupplier("DeleteJob"))
.build();
}
}
}
return getDeleteJobMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CancelJobRequest,
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
getCancelJobMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CancelJob",
requestType = com.google.cloud.storagebatchoperations.v1.CancelJobRequest.class,
responseType = com.google.cloud.storagebatchoperations.v1.CancelJobResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CancelJobRequest,
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
getCancelJobMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.storagebatchoperations.v1.CancelJobRequest,
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
getCancelJobMethod;
if ((getCancelJobMethod = StorageBatchOperationsGrpc.getCancelJobMethod) == null) {
synchronized (StorageBatchOperationsGrpc.class) {
if ((getCancelJobMethod = StorageBatchOperationsGrpc.getCancelJobMethod) == null) {
StorageBatchOperationsGrpc.getCancelJobMethod =
getCancelJobMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.storagebatchoperations.v1.CancelJobRequest,
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CancelJob"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.CancelJobRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.storagebatchoperations.v1.CancelJobResponse
.getDefaultInstance()))
.setSchemaDescriptor(
new StorageBatchOperationsMethodDescriptorSupplier("CancelJob"))
.build();
}
}
}
return getCancelJobMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static StorageBatchOperationsStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsStub>() {
@java.lang.Override
public StorageBatchOperationsStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsStub(channel, callOptions);
}
};
return StorageBatchOperationsStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static StorageBatchOperationsBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsBlockingV2Stub>() {
@java.lang.Override
public StorageBatchOperationsBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsBlockingV2Stub(channel, callOptions);
}
};
return StorageBatchOperationsBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static StorageBatchOperationsBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsBlockingStub>() {
@java.lang.Override
public StorageBatchOperationsBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsBlockingStub(channel, callOptions);
}
};
return StorageBatchOperationsBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static StorageBatchOperationsFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<StorageBatchOperationsFutureStub>() {
@java.lang.Override
public StorageBatchOperationsFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsFutureStub(channel, callOptions);
}
};
return StorageBatchOperationsFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Lists Jobs in a given project.
* </pre>
*/
default void listJobs(
com.google.cloud.storagebatchoperations.v1.ListJobsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getListJobsMethod(), responseObserver);
}
/**
*
*
* <pre>
* Gets a batch job.
* </pre>
*/
default void getJob(
com.google.cloud.storagebatchoperations.v1.GetJobRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.Job>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetJobMethod(), responseObserver);
}
/**
*
*
* <pre>
* Creates a batch job.
* </pre>
*/
default void createJob(
com.google.cloud.storagebatchoperations.v1.CreateJobRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCreateJobMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes a batch job.
* </pre>
*/
default void deleteJob(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getDeleteJobMethod(), responseObserver);
}
/**
*
*
* <pre>
* Cancels a batch job.
* </pre>
*/
default void cancelJob(
com.google.cloud.storagebatchoperations.v1.CancelJobRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCancelJobMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service StorageBatchOperations.
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public abstract static class StorageBatchOperationsImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return StorageBatchOperationsGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service StorageBatchOperations.
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public static final class StorageBatchOperationsStub
extends io.grpc.stub.AbstractAsyncStub<StorageBatchOperationsStub> {
private StorageBatchOperationsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected StorageBatchOperationsStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Jobs in a given project.
* </pre>
*/
public void listJobs(
com.google.cloud.storagebatchoperations.v1.ListJobsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListJobsMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Gets a batch job.
* </pre>
*/
public void getJob(
com.google.cloud.storagebatchoperations.v1.GetJobRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.Job>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetJobMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Creates a batch job.
* </pre>
*/
public void createJob(
com.google.cloud.storagebatchoperations.v1.CreateJobRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreateJobMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Deletes a batch job.
* </pre>
*/
public void deleteJob(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteJobMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Cancels a batch job.
* </pre>
*/
public void cancelJob(
com.google.cloud.storagebatchoperations.v1.CancelJobRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCancelJobMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service StorageBatchOperations.
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public static final class StorageBatchOperationsBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<StorageBatchOperationsBlockingV2Stub> {
private StorageBatchOperationsBlockingV2Stub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected StorageBatchOperationsBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Jobs in a given project.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.ListJobsResponse listJobs(
com.google.cloud.storagebatchoperations.v1.ListJobsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListJobsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets a batch job.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.Job getJob(
com.google.cloud.storagebatchoperations.v1.GetJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a batch job.
* </pre>
*/
public com.google.longrunning.Operation createJob(
com.google.cloud.storagebatchoperations.v1.CreateJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a batch job.
* </pre>
*/
public com.google.protobuf.Empty deleteJob(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Cancels a batch job.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.CancelJobResponse cancelJob(
com.google.cloud.storagebatchoperations.v1.CancelJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCancelJobMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service StorageBatchOperations.
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public static final class StorageBatchOperationsBlockingStub
extends io.grpc.stub.AbstractBlockingStub<StorageBatchOperationsBlockingStub> {
private StorageBatchOperationsBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected StorageBatchOperationsBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Jobs in a given project.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.ListJobsResponse listJobs(
com.google.cloud.storagebatchoperations.v1.ListJobsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListJobsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets a batch job.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.Job getJob(
com.google.cloud.storagebatchoperations.v1.GetJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a batch job.
* </pre>
*/
public com.google.longrunning.Operation createJob(
com.google.cloud.storagebatchoperations.v1.CreateJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a batch job.
* </pre>
*/
public com.google.protobuf.Empty deleteJob(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteJobMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Cancels a batch job.
* </pre>
*/
public com.google.cloud.storagebatchoperations.v1.CancelJobResponse cancelJob(
com.google.cloud.storagebatchoperations.v1.CancelJobRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCancelJobMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service
* StorageBatchOperations.
*
* <pre>
* Storage Batch Operations offers a managed experience to perform batch
* operations on millions of Cloud Storage objects in a serverless fashion. With
* this service, you can automate and simplify large scale API operations
* performed on Cloud Storage objects.
* </pre>
*/
public static final class StorageBatchOperationsFutureStub
extends io.grpc.stub.AbstractFutureStub<StorageBatchOperationsFutureStub> {
private StorageBatchOperationsFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected StorageBatchOperationsFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new StorageBatchOperationsFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Jobs in a given project.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>
listJobs(com.google.cloud.storagebatchoperations.v1.ListJobsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListJobsMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Gets a batch job.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.storagebatchoperations.v1.Job>
getJob(com.google.cloud.storagebatchoperations.v1.GetJobRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetJobMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Creates a batch job.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
createJob(com.google.cloud.storagebatchoperations.v1.CreateJobRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreateJobMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes a batch job.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteJob(
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteJobMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Cancels a batch job.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>
cancelJob(com.google.cloud.storagebatchoperations.v1.CancelJobRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCancelJobMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_JOBS = 0;
private static final int METHODID_GET_JOB = 1;
private static final int METHODID_CREATE_JOB = 2;
private static final int METHODID_DELETE_JOB = 3;
private static final int METHODID_CANCEL_JOB = 4;
private static final class MethodHandlers<Req, Resp>
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_LIST_JOBS:
serviceImpl.listJobs(
(com.google.cloud.storagebatchoperations.v1.ListJobsRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>)
responseObserver);
break;
case METHODID_GET_JOB:
serviceImpl.getJob(
(com.google.cloud.storagebatchoperations.v1.GetJobRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.storagebatchoperations.v1.Job>)
responseObserver);
break;
case METHODID_CREATE_JOB:
serviceImpl.createJob(
(com.google.cloud.storagebatchoperations.v1.CreateJobRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
case METHODID_DELETE_JOB:
serviceImpl.deleteJob(
(com.google.cloud.storagebatchoperations.v1.DeleteJobRequest) request,
(io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver);
break;
case METHODID_CANCEL_JOB:
serviceImpl.cancelJob(
(com.google.cloud.storagebatchoperations.v1.CancelJobRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>)
responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getListJobsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.storagebatchoperations.v1.ListJobsRequest,
com.google.cloud.storagebatchoperations.v1.ListJobsResponse>(
service, METHODID_LIST_JOBS)))
.addMethod(
getGetJobMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.storagebatchoperations.v1.GetJobRequest,
com.google.cloud.storagebatchoperations.v1.Job>(service, METHODID_GET_JOB)))
.addMethod(
getCreateJobMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.storagebatchoperations.v1.CreateJobRequest,
com.google.longrunning.Operation>(service, METHODID_CREATE_JOB)))
.addMethod(
getDeleteJobMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.storagebatchoperations.v1.DeleteJobRequest,
com.google.protobuf.Empty>(service, METHODID_DELETE_JOB)))
.addMethod(
getCancelJobMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.storagebatchoperations.v1.CancelJobRequest,
com.google.cloud.storagebatchoperations.v1.CancelJobResponse>(
service, METHODID_CANCEL_JOB)))
.build();
}
private abstract static class StorageBatchOperationsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
StorageBatchOperationsBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.storagebatchoperations.v1.StorageBatchOperationsProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("StorageBatchOperations");
}
}
private static final class StorageBatchOperationsFileDescriptorSupplier
extends StorageBatchOperationsBaseDescriptorSupplier {
StorageBatchOperationsFileDescriptorSupplier() {}
}
private static final class StorageBatchOperationsMethodDescriptorSupplier
extends StorageBatchOperationsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
StorageBatchOperationsMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (StorageBatchOperationsGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new StorageBatchOperationsFileDescriptorSupplier())
.addMethod(getListJobsMethod())
.addMethod(getGetJobMethod())
.addMethod(getCreateJobMethod())
.addMethod(getDeleteJobMethod())
.addMethod(getCancelJobMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 37,845 | java-alloydb/proto-google-cloud-alloydb-v1beta/src/main/java/com/google/cloud/alloydb/v1beta/ListBackupsRequest.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/alloydb/v1beta/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.alloydb.v1beta;
/**
*
*
* <pre>
* Message for requesting list of Backups
* </pre>
*
* Protobuf type {@code google.cloud.alloydb.v1beta.ListBackupsRequest}
*/
public final class ListBackupsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.alloydb.v1beta.ListBackupsRequest)
ListBackupsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListBackupsRequest.newBuilder() to construct.
private ListBackupsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListBackupsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListBackupsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.alloydb.v1beta.ServiceProto
.internal_static_google_cloud_alloydb_v1beta_ListBackupsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.alloydb.v1beta.ServiceProto
.internal_static_google_cloud_alloydb_v1beta_ListBackupsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.alloydb.v1beta.ListBackupsRequest.class,
com.google.cloud.alloydb.v1beta.ListBackupsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.alloydb.v1beta.ListBackupsRequest)) {
return super.equals(obj);
}
com.google.cloud.alloydb.v1beta.ListBackupsRequest other =
(com.google.cloud.alloydb.v1beta.ListBackupsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest 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.alloydb.v1beta.ListBackupsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest 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.alloydb.v1beta.ListBackupsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest 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.alloydb.v1beta.ListBackupsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest 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.alloydb.v1beta.ListBackupsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest 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.alloydb.v1beta.ListBackupsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Backups
* </pre>
*
* Protobuf type {@code google.cloud.alloydb.v1beta.ListBackupsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.alloydb.v1beta.ListBackupsRequest)
com.google.cloud.alloydb.v1beta.ListBackupsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.alloydb.v1beta.ServiceProto
.internal_static_google_cloud_alloydb_v1beta_ListBackupsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.alloydb.v1beta.ServiceProto
.internal_static_google_cloud_alloydb_v1beta_ListBackupsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.alloydb.v1beta.ListBackupsRequest.class,
com.google.cloud.alloydb.v1beta.ListBackupsRequest.Builder.class);
}
// Construct using com.google.cloud.alloydb.v1beta.ListBackupsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.alloydb.v1beta.ServiceProto
.internal_static_google_cloud_alloydb_v1beta_ListBackupsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.alloydb.v1beta.ListBackupsRequest getDefaultInstanceForType() {
return com.google.cloud.alloydb.v1beta.ListBackupsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.alloydb.v1beta.ListBackupsRequest build() {
com.google.cloud.alloydb.v1beta.ListBackupsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.alloydb.v1beta.ListBackupsRequest buildPartial() {
com.google.cloud.alloydb.v1beta.ListBackupsRequest result =
new com.google.cloud.alloydb.v1beta.ListBackupsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.alloydb.v1beta.ListBackupsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.alloydb.v1beta.ListBackupsRequest) {
return mergeFrom((com.google.cloud.alloydb.v1beta.ListBackupsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.alloydb.v1beta.ListBackupsRequest other) {
if (other == com.google.cloud.alloydb.v1beta.ListBackupsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListBackupsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.alloydb.v1beta.ListBackupsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.alloydb.v1beta.ListBackupsRequest)
private static final com.google.cloud.alloydb.v1beta.ListBackupsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.alloydb.v1beta.ListBackupsRequest();
}
public static com.google.cloud.alloydb.v1beta.ListBackupsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListBackupsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListBackupsRequest>() {
@java.lang.Override
public ListBackupsRequest 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<ListBackupsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListBackupsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.alloydb.v1beta.ListBackupsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,845 | java-tpu/proto-google-cloud-tpu-v2alpha1/src/main/java/com/google/cloud/tpu/v2alpha1/ListAcceleratorTypesRequest.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/tpu/v2alpha1/cloud_tpu.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.tpu.v2alpha1;
/**
*
*
* <pre>
* Request for
* [ListAcceleratorTypes][google.cloud.tpu.v2alpha1.Tpu.ListAcceleratorTypes].
* </pre>
*
* Protobuf type {@code google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest}
*/
public final class ListAcceleratorTypesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest)
ListAcceleratorTypesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAcceleratorTypesRequest.newBuilder() to construct.
private ListAcceleratorTypesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAcceleratorTypesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAcceleratorTypesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_ListAcceleratorTypesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_ListAcceleratorTypesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.class,
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource 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 parent resource 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 PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of items 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>
* The next_page_token value returned from a previous List request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous List request, if any.
* </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 = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 5;</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 = 5;</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 = 6;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</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>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, 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(5, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, 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.tpu.v2alpha1.ListAcceleratorTypesRequest)) {
return super.equals(obj);
}
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest other =
(com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest 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.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest 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.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest 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.tpu.v2alpha1.ListAcceleratorTypesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest 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.tpu.v2alpha1.ListAcceleratorTypesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest 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.tpu.v2alpha1.ListAcceleratorTypesRequest 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
* [ListAcceleratorTypes][google.cloud.tpu.v2alpha1.Tpu.ListAcceleratorTypes].
* </pre>
*
* Protobuf type {@code google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest)
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_ListAcceleratorTypesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_ListAcceleratorTypesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.class,
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.Builder.class);
}
// Construct using com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_ListAcceleratorTypesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest getDefaultInstanceForType() {
return com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest build() {
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest buildPartial() {
com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest result =
new com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest) {
return mergeFrom((com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest other) {
if (other == com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 42:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 42
case 50:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 50
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource 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 parent resource 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 parent resource 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 parent resource 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 parent resource 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 int pageSize_;
/**
*
*
* <pre>
* The maximum number of items 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 items 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 items 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>
* The next_page_token value returned from a previous List request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous List request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous List request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous List request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous List request, if any.
* </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>
* List filter.
* </pre>
*
* <code>string filter = 5;</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 = 5;</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 = 5;</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>
* List filter.
* </pre>
*
* <code>string filter = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 5;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</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>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</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>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Sort results.
* </pre>
*
* <code>string order_by = 6;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest)
private static final com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest();
}
public static com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAcceleratorTypesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListAcceleratorTypesRequest>() {
@java.lang.Override
public ListAcceleratorTypesRequest 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<ListAcceleratorTypesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAcceleratorTypesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.ListAcceleratorTypesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,056 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/PairwiseQuestionAnsweringQualityInput.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Input for pairwise question answering quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput}
*/
public final class PairwiseQuestionAnsweringQualityInput
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput)
PairwiseQuestionAnsweringQualityInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use PairwiseQuestionAnsweringQualityInput.newBuilder() to construct.
private PairwiseQuestionAnsweringQualityInput(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PairwiseQuestionAnsweringQualityInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new PairwiseQuestionAnsweringQualityInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseQuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseQuestionAnsweringQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput.class,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput.Builder
.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the metricSpec field is set.
*/
@java.lang.Override
public boolean hasMetricSpec() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance_;
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
@java.lang.Override
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getMetricSpec());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getInstance());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getMetricSpec());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getInstance());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput other =
(com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput) obj;
if (hasMetricSpec() != other.hasMetricSpec()) return false;
if (hasMetricSpec()) {
if (!getMetricSpec().equals(other.getMetricSpec())) return false;
}
if (hasInstance() != other.hasInstance()) return false;
if (hasInstance()) {
if (!getInstance().equals(other.getInstance())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasMetricSpec()) {
hash = (37 * hash) + METRIC_SPEC_FIELD_NUMBER;
hash = (53 * hash) + getMetricSpec().hashCode();
}
if (hasInstance()) {
hash = (37 * hash) + INSTANCE_FIELD_NUMBER;
hash = (53 * hash) + getInstance().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
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.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput 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.PairwiseQuestionAnsweringQualityInput prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Input for pairwise question answering quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput)
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseQuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseQuestionAnsweringQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput.class,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput.Builder
.class);
}
// Construct using
// com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getMetricSpecFieldBuilder();
getInstanceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
metricSpec_ = null;
if (metricSpecBuilder_ != null) {
metricSpecBuilder_.dispose();
metricSpecBuilder_ = null;
}
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseQuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput build() {
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
buildPartial() {
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput result =
new com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.metricSpec_ = metricSpecBuilder_ == null ? metricSpec_ : metricSpecBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.instance_ = instanceBuilder_ == null ? instance_ : instanceBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput) {
return mergeFrom(
(com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput other) {
if (other
== com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
.getDefaultInstance()) return this;
if (other.hasMetricSpec()) {
mergeMetricSpec(other.getMetricSpec());
}
if (other.hasInstance()) {
mergeInstance(other.getInstance());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getMetricSpecFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getInstanceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the metricSpec field is set.
*/
public boolean hasMetricSpec() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec value) {
if (metricSpecBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
metricSpec_ = value;
} else {
metricSpecBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec.Builder
builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
.getDefaultInstance()) {
getMetricSpecBuilder().mergeFrom(value);
} else {
metricSpec_ = value;
}
} else {
metricSpecBuilder_.mergeFrom(value);
}
if (metricSpec_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearMetricSpec() {
bitField0_ = (bitField0_ & ~0x00000001);
metricSpec_ = null;
if (metricSpecBuilder_ != null) {
metricSpecBuilder_.dispose();
metricSpecBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec
.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for pairwise question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualitySpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance.Builder,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearInstance() {
bitField0_ = (bitField0_ & ~0x00000002);
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Pairwise question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance.Builder,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInstance
.Builder,
com.google.cloud.aiplatform.v1beta1
.PairwiseQuestionAnsweringQualityInstanceOrBuilder>(
getInstance(), getParentForChildren(), isClean());
instance_ = null;
}
return instanceBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput)
private static final com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput();
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PairwiseQuestionAnsweringQualityInput> PARSER =
new com.google.protobuf.AbstractParser<PairwiseQuestionAnsweringQualityInput>() {
@java.lang.Override
public PairwiseQuestionAnsweringQualityInput 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<PairwiseQuestionAnsweringQualityInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PairwiseQuestionAnsweringQualityInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseQuestionAnsweringQualityInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,891 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/FunctionResponse.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/tool.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* The result output from a [FunctionCall] that contains a string representing
* the [FunctionDeclaration.name] and a structured JSON object containing any
* output from the function is used as context to the model. This should contain
* the result of a [FunctionCall] made based on model prediction.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.FunctionResponse}
*/
public final class FunctionResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.FunctionResponse)
FunctionResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use FunctionResponse.newBuilder() to construct.
private FunctionResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private FunctionResponse() {
id_ = "";
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new FunctionResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ToolProto
.internal_static_google_cloud_aiplatform_v1beta1_FunctionResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ToolProto
.internal_static_google_cloud_aiplatform_v1beta1_FunctionResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.FunctionResponse.class,
com.google.cloud.aiplatform.v1beta1.FunctionResponse.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object id_ = "";
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The id.
*/
@java.lang.Override
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</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 RESPONSE_FIELD_NUMBER = 2;
private com.google.protobuf.Struct response_;
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the response field is set.
*/
@java.lang.Override
public boolean hasResponse() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The response.
*/
@java.lang.Override
public com.google.protobuf.Struct getResponse() {
return response_ == null ? com.google.protobuf.Struct.getDefaultInstance() : response_;
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.protobuf.StructOrBuilder getResponseOrBuilder() {
return response_ == null ? com.google.protobuf.Struct.getDefaultInstance() : response_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getResponse());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, id_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getResponse());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, id_);
}
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.FunctionResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.FunctionResponse other =
(com.google.cloud.aiplatform.v1beta1.FunctionResponse) obj;
if (!getId().equals(other.getId())) return false;
if (!getName().equals(other.getName())) return false;
if (hasResponse() != other.hasResponse()) return false;
if (hasResponse()) {
if (!getResponse().equals(other.getResponse())) 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) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
if (hasResponse()) {
hash = (37 * hash) + RESPONSE_FIELD_NUMBER;
hash = (53 * hash) + getResponse().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse 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.FunctionResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse 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.FunctionResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse 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.FunctionResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse 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.FunctionResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse 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.FunctionResponse 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.FunctionResponse 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.FunctionResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The result output from a [FunctionCall] that contains a string representing
* the [FunctionDeclaration.name] and a structured JSON object containing any
* output from the function is used as context to the model. This should contain
* the result of a [FunctionCall] made based on model prediction.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.FunctionResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.FunctionResponse)
com.google.cloud.aiplatform.v1beta1.FunctionResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ToolProto
.internal_static_google_cloud_aiplatform_v1beta1_FunctionResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ToolProto
.internal_static_google_cloud_aiplatform_v1beta1_FunctionResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.FunctionResponse.class,
com.google.cloud.aiplatform.v1beta1.FunctionResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.FunctionResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getResponseFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
id_ = "";
name_ = "";
response_ = null;
if (responseBuilder_ != null) {
responseBuilder_.dispose();
responseBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.ToolProto
.internal_static_google_cloud_aiplatform_v1beta1_FunctionResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.FunctionResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.FunctionResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.FunctionResponse build() {
com.google.cloud.aiplatform.v1beta1.FunctionResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.FunctionResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.FunctionResponse result =
new com.google.cloud.aiplatform.v1beta1.FunctionResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.FunctionResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.id_ = id_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.name_ = name_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.response_ = responseBuilder_ == null ? response_ : responseBuilder_.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.aiplatform.v1beta1.FunctionResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.FunctionResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.FunctionResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.FunctionResponse.getDefaultInstance())
return this;
if (!other.getId().isEmpty()) {
id_ = other.id_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasResponse()) {
mergeResponse(other.getResponse());
}
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_ |= 0x00000002;
break;
} // case 10
case 18:
{
input.readMessage(getResponseFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 18
case 26:
{
id_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
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 id_ = "";
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The id.
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for id.
*/
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearId() {
id_ = getDefaultInstance().getId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The id of the function call this response is for. Populated by
* the client to match the corresponding function call `id`.
* </pre>
*
* <code>string id = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</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_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the function to call.
* Matches [FunctionDeclaration.name] and [FunctionCall.name].
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</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_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.Struct response_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
responseBuilder_;
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the response field is set.
*/
public boolean hasResponse() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The response.
*/
public com.google.protobuf.Struct getResponse() {
if (responseBuilder_ == null) {
return response_ == null ? com.google.protobuf.Struct.getDefaultInstance() : response_;
} else {
return responseBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setResponse(com.google.protobuf.Struct value) {
if (responseBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
response_ = value;
} else {
responseBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setResponse(com.google.protobuf.Struct.Builder builderForValue) {
if (responseBuilder_ == null) {
response_ = builderForValue.build();
} else {
responseBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeResponse(com.google.protobuf.Struct value) {
if (responseBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& response_ != null
&& response_ != com.google.protobuf.Struct.getDefaultInstance()) {
getResponseBuilder().mergeFrom(value);
} else {
response_ = value;
}
} else {
responseBuilder_.mergeFrom(value);
}
if (response_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearResponse() {
bitField0_ = (bitField0_ & ~0x00000004);
response_ = null;
if (responseBuilder_ != null) {
responseBuilder_.dispose();
responseBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.protobuf.Struct.Builder getResponseBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getResponseFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.protobuf.StructOrBuilder getResponseOrBuilder() {
if (responseBuilder_ != null) {
return responseBuilder_.getMessageOrBuilder();
} else {
return response_ == null ? com.google.protobuf.Struct.getDefaultInstance() : response_;
}
}
/**
*
*
* <pre>
* Required. The function response in JSON object format.
* Use "output" key to specify function output and "error" key to specify
* error details (if any). If "output" and "error" keys are not specified,
* then whole "response" is treated as function output.
* </pre>
*
* <code>.google.protobuf.Struct response = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
getResponseFieldBuilder() {
if (responseBuilder_ == null) {
responseBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>(
getResponse(), getParentForChildren(), isClean());
response_ = null;
}
return responseBuilder_;
}
@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.FunctionResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.FunctionResponse)
private static final com.google.cloud.aiplatform.v1beta1.FunctionResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.FunctionResponse();
}
public static com.google.cloud.aiplatform.v1beta1.FunctionResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<FunctionResponse> PARSER =
new com.google.protobuf.AbstractParser<FunctionResponse>() {
@java.lang.Override
public FunctionResponse 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<FunctionResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<FunctionResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.FunctionResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,996 | java-recommender/proto-google-cloud-recommender-v1beta1/src/main/java/com/google/cloud/recommender/v1beta1/ListRecommendersResponse.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/v1beta1/recommender_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.recommender.v1beta1;
/**
*
*
* <pre>
* Response for the `ListRecommender` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1beta1.ListRecommendersResponse}
*/
public final class ListRecommendersResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recommender.v1beta1.ListRecommendersResponse)
ListRecommendersResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListRecommendersResponse.newBuilder() to construct.
private ListRecommendersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListRecommendersResponse() {
recommenders_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListRecommendersResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1beta1.RecommenderProto
.internal_static_google_cloud_recommender_v1beta1_ListRecommendersResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1beta1.RecommenderProto
.internal_static_google_cloud_recommender_v1beta1_ListRecommendersResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1beta1.ListRecommendersResponse.class,
com.google.cloud.recommender.v1beta1.ListRecommendersResponse.Builder.class);
}
public static final int RECOMMENDERS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.recommender.v1beta1.RecommenderType> recommenders_;
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.recommender.v1beta1.RecommenderType>
getRecommendersList() {
return recommenders_;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder>
getRecommendersOrBuilderList() {
return recommenders_;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
@java.lang.Override
public int getRecommendersCount() {
return recommenders_.size();
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
@java.lang.Override
public com.google.cloud.recommender.v1beta1.RecommenderType getRecommenders(int index) {
return recommenders_.get(index);
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
@java.lang.Override
public com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder getRecommendersOrBuilder(
int index) {
return recommenders_.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 < recommenders_.size(); i++) {
output.writeMessage(1, recommenders_.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 < recommenders_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, recommenders_.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.recommender.v1beta1.ListRecommendersResponse)) {
return super.equals(obj);
}
com.google.cloud.recommender.v1beta1.ListRecommendersResponse other =
(com.google.cloud.recommender.v1beta1.ListRecommendersResponse) obj;
if (!getRecommendersList().equals(other.getRecommendersList())) 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 (getRecommendersCount() > 0) {
hash = (37 * hash) + RECOMMENDERS_FIELD_NUMBER;
hash = (53 * hash) + getRecommendersList().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.recommender.v1beta1.ListRecommendersResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.v1beta1.ListRecommendersResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.v1beta1.ListRecommendersResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.v1beta1.ListRecommendersResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.v1beta1.ListRecommendersResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.v1beta1.ListRecommendersResponse 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 `ListRecommender` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1beta1.ListRecommendersResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recommender.v1beta1.ListRecommendersResponse)
com.google.cloud.recommender.v1beta1.ListRecommendersResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1beta1.RecommenderProto
.internal_static_google_cloud_recommender_v1beta1_ListRecommendersResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1beta1.RecommenderProto
.internal_static_google_cloud_recommender_v1beta1_ListRecommendersResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1beta1.ListRecommendersResponse.class,
com.google.cloud.recommender.v1beta1.ListRecommendersResponse.Builder.class);
}
// Construct using com.google.cloud.recommender.v1beta1.ListRecommendersResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (recommendersBuilder_ == null) {
recommenders_ = java.util.Collections.emptyList();
} else {
recommenders_ = null;
recommendersBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.recommender.v1beta1.RecommenderProto
.internal_static_google_cloud_recommender_v1beta1_ListRecommendersResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.ListRecommendersResponse
getDefaultInstanceForType() {
return com.google.cloud.recommender.v1beta1.ListRecommendersResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.ListRecommendersResponse build() {
com.google.cloud.recommender.v1beta1.ListRecommendersResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.ListRecommendersResponse buildPartial() {
com.google.cloud.recommender.v1beta1.ListRecommendersResponse result =
new com.google.cloud.recommender.v1beta1.ListRecommendersResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.recommender.v1beta1.ListRecommendersResponse result) {
if (recommendersBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
recommenders_ = java.util.Collections.unmodifiableList(recommenders_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.recommenders_ = recommenders_;
} else {
result.recommenders_ = recommendersBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.recommender.v1beta1.ListRecommendersResponse 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.recommender.v1beta1.ListRecommendersResponse) {
return mergeFrom((com.google.cloud.recommender.v1beta1.ListRecommendersResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.recommender.v1beta1.ListRecommendersResponse other) {
if (other
== com.google.cloud.recommender.v1beta1.ListRecommendersResponse.getDefaultInstance())
return this;
if (recommendersBuilder_ == null) {
if (!other.recommenders_.isEmpty()) {
if (recommenders_.isEmpty()) {
recommenders_ = other.recommenders_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureRecommendersIsMutable();
recommenders_.addAll(other.recommenders_);
}
onChanged();
}
} else {
if (!other.recommenders_.isEmpty()) {
if (recommendersBuilder_.isEmpty()) {
recommendersBuilder_.dispose();
recommendersBuilder_ = null;
recommenders_ = other.recommenders_;
bitField0_ = (bitField0_ & ~0x00000001);
recommendersBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getRecommendersFieldBuilder()
: null;
} else {
recommendersBuilder_.addAllMessages(other.recommenders_);
}
}
}
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.recommender.v1beta1.RecommenderType m =
input.readMessage(
com.google.cloud.recommender.v1beta1.RecommenderType.parser(),
extensionRegistry);
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
recommenders_.add(m);
} else {
recommendersBuilder_.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.recommender.v1beta1.RecommenderType> recommenders_ =
java.util.Collections.emptyList();
private void ensureRecommendersIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
recommenders_ =
new java.util.ArrayList<com.google.cloud.recommender.v1beta1.RecommenderType>(
recommenders_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.recommender.v1beta1.RecommenderType,
com.google.cloud.recommender.v1beta1.RecommenderType.Builder,
com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder>
recommendersBuilder_;
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public java.util.List<com.google.cloud.recommender.v1beta1.RecommenderType>
getRecommendersList() {
if (recommendersBuilder_ == null) {
return java.util.Collections.unmodifiableList(recommenders_);
} else {
return recommendersBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public int getRecommendersCount() {
if (recommendersBuilder_ == null) {
return recommenders_.size();
} else {
return recommendersBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public com.google.cloud.recommender.v1beta1.RecommenderType getRecommenders(int index) {
if (recommendersBuilder_ == null) {
return recommenders_.get(index);
} else {
return recommendersBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder setRecommenders(
int index, com.google.cloud.recommender.v1beta1.RecommenderType value) {
if (recommendersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecommendersIsMutable();
recommenders_.set(index, value);
onChanged();
} else {
recommendersBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder setRecommenders(
int index, com.google.cloud.recommender.v1beta1.RecommenderType.Builder builderForValue) {
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
recommenders_.set(index, builderForValue.build());
onChanged();
} else {
recommendersBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder addRecommenders(com.google.cloud.recommender.v1beta1.RecommenderType value) {
if (recommendersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecommendersIsMutable();
recommenders_.add(value);
onChanged();
} else {
recommendersBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder addRecommenders(
int index, com.google.cloud.recommender.v1beta1.RecommenderType value) {
if (recommendersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureRecommendersIsMutable();
recommenders_.add(index, value);
onChanged();
} else {
recommendersBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder addRecommenders(
com.google.cloud.recommender.v1beta1.RecommenderType.Builder builderForValue) {
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
recommenders_.add(builderForValue.build());
onChanged();
} else {
recommendersBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder addRecommenders(
int index, com.google.cloud.recommender.v1beta1.RecommenderType.Builder builderForValue) {
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
recommenders_.add(index, builderForValue.build());
onChanged();
} else {
recommendersBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder addAllRecommenders(
java.lang.Iterable<? extends com.google.cloud.recommender.v1beta1.RecommenderType> values) {
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, recommenders_);
onChanged();
} else {
recommendersBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder clearRecommenders() {
if (recommendersBuilder_ == null) {
recommenders_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
recommendersBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public Builder removeRecommenders(int index) {
if (recommendersBuilder_ == null) {
ensureRecommendersIsMutable();
recommenders_.remove(index);
onChanged();
} else {
recommendersBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public com.google.cloud.recommender.v1beta1.RecommenderType.Builder getRecommendersBuilder(
int index) {
return getRecommendersFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder getRecommendersOrBuilder(
int index) {
if (recommendersBuilder_ == null) {
return recommenders_.get(index);
} else {
return recommendersBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public java.util.List<? extends com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder>
getRecommendersOrBuilderList() {
if (recommendersBuilder_ != null) {
return recommendersBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(recommenders_);
}
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public com.google.cloud.recommender.v1beta1.RecommenderType.Builder addRecommendersBuilder() {
return getRecommendersFieldBuilder()
.addBuilder(com.google.cloud.recommender.v1beta1.RecommenderType.getDefaultInstance());
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public com.google.cloud.recommender.v1beta1.RecommenderType.Builder addRecommendersBuilder(
int index) {
return getRecommendersFieldBuilder()
.addBuilder(
index, com.google.cloud.recommender.v1beta1.RecommenderType.getDefaultInstance());
}
/**
*
*
* <pre>
* The set of recommenders available
* </pre>
*
* <code>repeated .google.cloud.recommender.v1beta1.RecommenderType recommenders = 1;</code>
*/
public java.util.List<com.google.cloud.recommender.v1beta1.RecommenderType.Builder>
getRecommendersBuilderList() {
return getRecommendersFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.recommender.v1beta1.RecommenderType,
com.google.cloud.recommender.v1beta1.RecommenderType.Builder,
com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder>
getRecommendersFieldBuilder() {
if (recommendersBuilder_ == null) {
recommendersBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.recommender.v1beta1.RecommenderType,
com.google.cloud.recommender.v1beta1.RecommenderType.Builder,
com.google.cloud.recommender.v1beta1.RecommenderTypeOrBuilder>(
recommenders_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
recommenders_ = null;
}
return recommendersBuilder_;
}
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.recommender.v1beta1.ListRecommendersResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.ListRecommendersResponse)
private static final com.google.cloud.recommender.v1beta1.ListRecommendersResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.recommender.v1beta1.ListRecommendersResponse();
}
public static com.google.cloud.recommender.v1beta1.ListRecommendersResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListRecommendersResponse> PARSER =
new com.google.protobuf.AbstractParser<ListRecommendersResponse>() {
@java.lang.Override
public ListRecommendersResponse 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<ListRecommendersResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListRecommendersResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.ListRecommendersResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,099 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListPersistentResourcesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/persistent_resource_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Response message for
* [PersistentResourceService.ListPersistentResources][google.cloud.aiplatform.v1.PersistentResourceService.ListPersistentResources]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListPersistentResourcesResponse}
*/
public final class ListPersistentResourcesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListPersistentResourcesResponse)
ListPersistentResourcesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListPersistentResourcesResponse.newBuilder() to construct.
private ListPersistentResourcesResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListPersistentResourcesResponse() {
persistentResources_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListPersistentResourcesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_ListPersistentResourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_ListPersistentResourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.class,
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.Builder.class);
}
public static final int PERSISTENT_RESOURCES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1.PersistentResource> persistentResources_;
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1.PersistentResource>
getPersistentResourcesList() {
return persistentResources_;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
getPersistentResourcesOrBuilderList() {
return persistentResources_;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;</code>
*/
@java.lang.Override
public int getPersistentResourcesCount() {
return persistentResources_.size();
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PersistentResource getPersistentResources(int index) {
return persistentResources_.get(index);
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder getPersistentResourcesOrBuilder(
int index) {
return persistentResources_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < persistentResources_.size(); i++) {
output.writeMessage(1, persistentResources_.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 < persistentResources_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(1, persistentResources_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse other =
(com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse) obj;
if (!getPersistentResourcesList().equals(other.getPersistentResourcesList())) 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 (getPersistentResourcesCount() > 0) {
hash = (37 * hash) + PERSISTENT_RESOURCES_FIELD_NUMBER;
hash = (53 * hash) + getPersistentResourcesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse 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
* [PersistentResourceService.ListPersistentResources][google.cloud.aiplatform.v1.PersistentResourceService.ListPersistentResources]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListPersistentResourcesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListPersistentResourcesResponse)
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_ListPersistentResourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_ListPersistentResourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.class,
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (persistentResourcesBuilder_ == null) {
persistentResources_ = java.util.Collections.emptyList();
} else {
persistentResources_ = null;
persistentResourcesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_ListPersistentResourcesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse build() {
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse buildPartial() {
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse result =
new com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse result) {
if (persistentResourcesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
persistentResources_ = java.util.Collections.unmodifiableList(persistentResources_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.persistentResources_ = persistentResources_;
} else {
result.persistentResources_ = persistentResourcesBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse other) {
if (other
== com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse.getDefaultInstance())
return this;
if (persistentResourcesBuilder_ == null) {
if (!other.persistentResources_.isEmpty()) {
if (persistentResources_.isEmpty()) {
persistentResources_ = other.persistentResources_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePersistentResourcesIsMutable();
persistentResources_.addAll(other.persistentResources_);
}
onChanged();
}
} else {
if (!other.persistentResources_.isEmpty()) {
if (persistentResourcesBuilder_.isEmpty()) {
persistentResourcesBuilder_.dispose();
persistentResourcesBuilder_ = null;
persistentResources_ = other.persistentResources_;
bitField0_ = (bitField0_ & ~0x00000001);
persistentResourcesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPersistentResourcesFieldBuilder()
: null;
} else {
persistentResourcesBuilder_.addAllMessages(other.persistentResources_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1.PersistentResource m =
input.readMessage(
com.google.cloud.aiplatform.v1.PersistentResource.parser(),
extensionRegistry);
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
persistentResources_.add(m);
} else {
persistentResourcesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1.PersistentResource> persistentResources_ =
java.util.Collections.emptyList();
private void ensurePersistentResourcesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
persistentResources_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1.PersistentResource>(
persistentResources_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
persistentResourcesBuilder_;
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.PersistentResource>
getPersistentResourcesList() {
if (persistentResourcesBuilder_ == null) {
return java.util.Collections.unmodifiableList(persistentResources_);
} else {
return persistentResourcesBuilder_.getMessageList();
}
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public int getPersistentResourcesCount() {
if (persistentResourcesBuilder_ == null) {
return persistentResources_.size();
} else {
return persistentResourcesBuilder_.getCount();
}
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResource getPersistentResources(int index) {
if (persistentResourcesBuilder_ == null) {
return persistentResources_.get(index);
} else {
return persistentResourcesBuilder_.getMessage(index);
}
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder setPersistentResources(
int index, com.google.cloud.aiplatform.v1.PersistentResource value) {
if (persistentResourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePersistentResourcesIsMutable();
persistentResources_.set(index, value);
onChanged();
} else {
persistentResourcesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder setPersistentResources(
int index, com.google.cloud.aiplatform.v1.PersistentResource.Builder builderForValue) {
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
persistentResources_.set(index, builderForValue.build());
onChanged();
} else {
persistentResourcesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder addPersistentResources(com.google.cloud.aiplatform.v1.PersistentResource value) {
if (persistentResourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePersistentResourcesIsMutable();
persistentResources_.add(value);
onChanged();
} else {
persistentResourcesBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder addPersistentResources(
int index, com.google.cloud.aiplatform.v1.PersistentResource value) {
if (persistentResourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePersistentResourcesIsMutable();
persistentResources_.add(index, value);
onChanged();
} else {
persistentResourcesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder addPersistentResources(
com.google.cloud.aiplatform.v1.PersistentResource.Builder builderForValue) {
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
persistentResources_.add(builderForValue.build());
onChanged();
} else {
persistentResourcesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder addPersistentResources(
int index, com.google.cloud.aiplatform.v1.PersistentResource.Builder builderForValue) {
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
persistentResources_.add(index, builderForValue.build());
onChanged();
} else {
persistentResourcesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder addAllPersistentResources(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.PersistentResource> values) {
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, persistentResources_);
onChanged();
} else {
persistentResourcesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder clearPersistentResources() {
if (persistentResourcesBuilder_ == null) {
persistentResources_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
persistentResourcesBuilder_.clear();
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public Builder removePersistentResources(int index) {
if (persistentResourcesBuilder_ == null) {
ensurePersistentResourcesIsMutable();
persistentResources_.remove(index);
onChanged();
} else {
persistentResourcesBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResource.Builder getPersistentResourcesBuilder(
int index) {
return getPersistentResourcesFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder
getPersistentResourcesOrBuilder(int index) {
if (persistentResourcesBuilder_ == null) {
return persistentResources_.get(index);
} else {
return persistentResourcesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
getPersistentResourcesOrBuilderList() {
if (persistentResourcesBuilder_ != null) {
return persistentResourcesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(persistentResources_);
}
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResource.Builder
addPersistentResourcesBuilder() {
return getPersistentResourcesFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance());
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResource.Builder addPersistentResourcesBuilder(
int index) {
return getPersistentResourcesFieldBuilder()
.addBuilder(
index, com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance());
}
/**
* <code>repeated .google.cloud.aiplatform.v1.PersistentResource persistent_resources = 1;
* </code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.PersistentResource.Builder>
getPersistentResourcesBuilderList() {
return getPersistentResourcesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
getPersistentResourcesFieldBuilder() {
if (persistentResourcesBuilder_ == null) {
persistentResourcesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>(
persistentResources_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
persistentResources_ = null;
}
return persistentResourcesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListPersistentResourcesRequest.page_token][google.cloud.aiplatform.v1.ListPersistentResourcesRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListPersistentResourcesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListPersistentResourcesResponse)
private static final com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse();
}
public static com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListPersistentResourcesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListPersistentResourcesResponse>() {
@java.lang.Override
public ListPersistentResourcesResponse 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<ListPersistentResourcesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListPersistentResourcesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListPersistentResourcesResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/manifoldcf | 38,014 | connectors/email/connector/src/main/java/org/apache/manifoldcf/crawler/notifications/email/EmailConnector.java | /* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.notifications.email;
import org.apache.commons.lang.StringUtils;
import org.apache.manifoldcf.agents.interfaces.ServiceInterruption;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.crawler.system.Logging;
import java.io.*;
import java.util.*;
import javax.mail.*;
/**
*/
public class EmailConnector extends org.apache.manifoldcf.crawler.notifications.BaseNotificationConnector {
protected final static long SESSION_EXPIRATION_MILLISECONDS = 300000L;
// Local variables.
protected long sessionExpiration = -1L;
// Parameters for establishing a session
protected String server = null;
protected String portString = null;
protected String username = null;
protected String password = null;
protected Properties properties = null;
// Local session handle
protected EmailSession session = null;
//////////////////////////////////Start of Basic Connector Methods/////////////////////////
/**
* Connect.
*
* @param configParameters is the set of configuration parameters, which
* in this case describe the root directory.
*/
@Override
public void connect(ConfigParams configParameters) {
super.connect(configParameters);
this.server = configParameters.getParameter(EmailConfig.SERVER_PARAM);
this.portString = configParameters.getParameter(EmailConfig.PORT_PARAM);
this.username = configParameters.getParameter(EmailConfig.USERNAME_PARAM);
this.password = configParameters.getObfuscatedParameter(EmailConfig.PASSWORD_PARAM);
this.properties = new Properties();
int i = 0;
while (i < configParameters.getChildCount()) //In post property set is added as a configuration node
{
ConfigNode cn = configParameters.getChild(i++);
if (cn.getType().equals(EmailConfig.NODE_PROPERTIES)) {
String findParameterName = cn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
String findParameterValue = cn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
this.properties.setProperty(findParameterName, findParameterValue);
}
}
}
/**
* Close the connection. Call this before discarding this instance of the
* repository connector.
*/
@Override
public void disconnect()
throws ManifoldCFException {
this.server = null;
this.portString = null;
this.username = null;
this.password = null;
this.properties = null;
finalizeConnection();
super.disconnect();
}
/**
* This method is periodically called for all connectors that are connected but not
* in active use.
*/
@Override
public void poll() throws ManifoldCFException {
if (session != null)
{
if (System.currentTimeMillis() >= sessionExpiration)
finalizeConnection();
}
}
/**
* Test the connection. Returns a string describing the connection integrity.
*
* @return the connection's status as a displayable string.
*/
@Override
public String check()
throws ManifoldCFException {
try {
checkConnection();
return super.check();
} catch (ServiceInterruption e) {
return "Connection temporarily failed: " + e.getMessage();
} catch (ManifoldCFException e) {
return "Connection failed: " + e.getMessage();
}
}
protected void checkConnection() throws ManifoldCFException, ServiceInterruption {
// Force a re-connection
finalizeConnection();
getSession();
try {
CheckConnectionThread cct = new CheckConnectionThread(session);
cct.start();
cct.finishUp();
} catch (InterruptedException e) {
throw new ManifoldCFException(e.getMessage(),ManifoldCFException.INTERRUPTED);
} catch (MessagingException e) {
handleMessagingException(e,"checking the connection");
}
}
protected void getSession()
throws ManifoldCFException, ServiceInterruption {
if (session == null) {
// Check that all the required parameters are there.
if (server == null)
throw new ManifoldCFException("Missing server parameter");
if (properties == null)
throw new ManifoldCFException("Missing server properties");
// Create a session.
int port;
if (portString != null && portString.length() > 0)
{
try
{
port = Integer.parseInt(portString);
}
catch (NumberFormatException e)
{
throw new ManifoldCFException("Port number has bad format: "+e.getMessage(),e);
}
}
else
port = -1;
try {
ConnectThread connectThread = new ConnectThread(server, port, username, password, properties);
connectThread.start();
session = connectThread.finishUp();
} catch (InterruptedException e) {
throw new ManifoldCFException(e.getMessage(),ManifoldCFException.INTERRUPTED);
} catch (MessagingException e) {
handleMessagingException(e, "connecting");
}
}
sessionExpiration = System.currentTimeMillis() + SESSION_EXPIRATION_MILLISECONDS;
}
protected void finalizeConnection() {
if (session != null) {
try {
CloseSessionThread closeSessionThread = new CloseSessionThread(session);
closeSessionThread.start();
closeSessionThread.finishUp();
} catch (InterruptedException e) {
} catch (MessagingException e) {
Logging.connectors.warn("Error while closing connection to server: " + e.getMessage(),e);
} finally {
session = null;
}
}
}
///////////////////////////////End of Basic Connector Methods////////////////////////////////////////
//////////////////////////////Start of Notification Connector Method///////////////////////////////////
/** Notify of job stop due to error abort.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobStopErrorAbort(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_ERRORABORTED);
}
/** Notify of job stop due to manual abort.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobStopManualAbort(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_MANUALABORTED);
}
/** Notify of job stop due to manual pause.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobStopManualPause(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_MANUALPAUSED);
}
/** Notify of job stop due to schedule pause.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobStopSchedulePause(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_SCHEDULEPAUSED);
}
/** Notify of job stop due to restart.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobStopRestart(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_RESTARTED);
}
/** Notify of job end.
*@param spec is the notification specification.
*/
@Override
public void notifyOfJobEnd(final Specification spec)
throws ManifoldCFException, ServiceInterruption {
sendMail(spec, EmailConfig.NODE_FINISHED);
}
protected void sendMail(final Specification spec, final String nodeType)
throws ManifoldCFException, ServiceInterruption
{
final List<String> to = new ArrayList<String>();
String from = null;
String subject = "";
String body = "";
for (int i = 0; i < spec.getChildCount(); i++) {
SpecificationNode sn = spec.getChild(i);
if (sn.getType().equals(EmailConfig.NODE_TO))
to.addAll(splitAtCommaAndTrim(sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE)));
else if (sn.getType().equals(EmailConfig.NODE_FROM))
from = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
else if (sn.getType().equals(EmailConfig.NODE_SUBJECT))
subject = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
else if (sn.getType().equals(EmailConfig.NODE_BODY))
body = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
}
// Look for node of the specified type
if (nodeType != null)
{
for (int i = 0; i < spec.getChildCount(); i++) {
SpecificationNode childNode = spec.getChild(i);
if (childNode.getType().equals(nodeType))
{
for (int j = 0; j < childNode.getChildCount(); j++) {
SpecificationNode sn = childNode.getChild(j);
if (sn.getType().equals(EmailConfig.NODE_TO)) {
to.addAll(splitAtCommaAndTrim(sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE)));
}
else if (sn.getType().equals(EmailConfig.NODE_FROM))
from = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
else if (sn.getType().equals(EmailConfig.NODE_SUBJECT))
subject = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
else if (sn.getType().equals(EmailConfig.NODE_BODY))
body = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
}
}
}
}
if (to.size() == 0)
return;
// Construct and send an email
getSession();
SendThread st = new SendThread(session,to,from,subject,body);
st.start();
try {
st.finishUp();
} catch (InterruptedException e) {
throw new ManifoldCFException(e.getMessage(),ManifoldCFException.INTERRUPTED);
} catch (MessagingException e) {
handleMessagingException(e,"sending email");
}
}
private List<String> splitAtCommaAndTrim(String input) {
List<String> result = new ArrayList<>();
if (input != null) {
result.addAll(Arrays.asList(input.split("\\s*,\\s*")));
}
return result;
}
//////////////////////////////End of Notification Connector Methods///////////////////////////////////
///////////////////////////////////////Start of Configuration UI/////////////////////////////////////
/**
* Output the configuration header section.
* This method is called in the head section of the connector's configuration page. Its purpose is to
* add the required tabs to the list, and to output any javascript methods that might be needed by
* the configuration editing HTML.
* The connector does not need to be connected for this method to be called.
*
* @param threadContext is the local thread context.
* @param out is the output to which any HTML should be sent.
* @param locale is the desired locale.
* @param parameters are the configuration parameters, as they currently exist, for this connection being configured.
* @param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector.
*/
@Override
public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters, List<String> tabsArray)
throws ManifoldCFException, IOException {
tabsArray.add(Messages.getString(locale, "EmailConnector.Server"));
// Map the parameters
Map<String, Object> paramMap = new HashMap<String, Object>();
// Fill in the parameters from each tab
fillInServerConfigurationMap(paramMap, out, parameters);
// Output the Javascript - only one Velocity template for all tabs
Messages.outputResourceWithVelocity(out, locale, "ConfigurationHeader.js", paramMap);
}
@Override
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters, String tabName)
throws ManifoldCFException, IOException {
// Output the Server tab
Map<String, Object> paramMap = new HashMap<String, Object>();
// Set the tab name
paramMap.put("TabName", tabName);
// Fill in the parameters
fillInServerConfigurationMap(paramMap, out, parameters);
Messages.outputResourceWithVelocity(out, locale, "Configuration_Server.html", paramMap);
}
private static void fillInServerConfigurationMap(Map<String, Object> paramMap, IPasswordMapperActivity mapper, ConfigParams parameters) {
int i = 0;
String username = parameters.getParameter(EmailConfig.USERNAME_PARAM);
String password = parameters.getObfuscatedParameter(EmailConfig.PASSWORD_PARAM);
String server = parameters.getParameter(EmailConfig.SERVER_PARAM);
String port = parameters.getParameter(EmailConfig.PORT_PARAM);
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
while (i < parameters.getChildCount()) //In post property set is added as a configuration node
{
ConfigNode cn = parameters.getChild(i++);
if (cn.getType().equals(EmailConfig.NODE_PROPERTIES)) {
String findParameterName = cn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
String findParameterValue = cn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
Map<String, String> row = new HashMap<String, String>();
row.put("name", findParameterName);
row.put("value", findParameterValue);
list.add(row);
}
}
if (username == null)
username = StringUtils.EMPTY;
if (password == null)
password = StringUtils.EMPTY;
else
password = mapper.mapPasswordToKey(password);
if (server == null)
server = StringUtils.EMPTY;
if (port == null)
port = EmailConfig.PORT_DEFAULT_VALUE;
paramMap.put("USERNAME", username);
paramMap.put("PASSWORD", password);
paramMap.put("SERVER", server);
paramMap.put("PORT", port);
paramMap.put("PROPERTIES", list);
}
/**
* Process a configuration post.
* This method is called at the start of the connector's configuration page, whenever there is a possibility
* that form data for a connection has been posted. Its purpose is to gather form information and modify
* the configuration parameters accordingly.
* The name of the posted form is always "editconnection".
* The connector does not need to be connected for this method to be called.
*
* @param threadContext is the local thread context.
* @param variableContext is the set of variables available from the post, including binary file post information.
* @param parameters are the configuration parameters, as they currently exist, for this connection being configured.
* @return null if all is well, or a string error message if there is an error that should prevent saving of the
* connection (and cause a redirection to an error page).
*/
@Override
public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext,
ConfigParams parameters) throws ManifoldCFException {
String userName = variableContext.getParameter("username");
if (userName != null)
parameters.setParameter(EmailConfig.USERNAME_PARAM, userName);
String password = variableContext.getParameter("password");
if (password != null)
parameters.setObfuscatedParameter(EmailConfig.PASSWORD_PARAM, variableContext.mapKeyToPassword(password));
String server = variableContext.getParameter("server");
if (server != null)
parameters.setParameter(EmailConfig.SERVER_PARAM, server);
String port = variableContext.getParameter("port");
if (port != null)
parameters.setParameter(EmailConfig.PORT_PARAM, port);
// Remove old find parameter document specification information
removeNodes(parameters, EmailConfig.NODE_PROPERTIES);
// Parse the number of records that were posted
String findCountString = variableContext.getParameter("findcount");
if (findCountString != null) {
int findCount = Integer.parseInt(findCountString);
// Loop throught them and add new server properties
int i = 0;
while (i < findCount) {
String suffix = "_" + Integer.toString(i++);
// Only add the name/value if the item was not deleted.
String findParameterOp = variableContext.getParameter("findop" + suffix);
if (findParameterOp == null || !findParameterOp.equals("Delete")) {
String findParameterName = variableContext.getParameter("findname" + suffix);
String findParameterValue = variableContext.getParameter("findvalue" + suffix);
addFindParameterNode(parameters, findParameterName, findParameterValue);
}
}
}
// Now, look for a global "Add" operation
String operation = variableContext.getParameter("findop");
if (operation != null && operation.equals("Add")) {
// Pick up the global parameter name and value
String findParameterName = variableContext.getParameter("findname");
String findParameterValue = variableContext.getParameter("findvalue");
addFindParameterNode(parameters, findParameterName, findParameterValue);
}
return null;
}
/**
* View configuration. This method is called in the body section of the
* connector's view configuration page. Its purpose is to present the
* connection information to the user. The coder can presume that the HTML that
* is output from this configuration will be within appropriate <html> and
* <body> tags.
*
* @param threadContext is the local thread context.
* @param out is the output to which any HTML should be sent.
* @param parameters are the configuration parameters, as they currently exist, for
* this connection being configured.
*/
@Override
public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
// Fill in map from each tab
fillInServerConfigurationMap(paramMap, out, parameters);
Messages.outputResourceWithVelocity(out, locale, "ConfigurationView.html", paramMap);
}
/////////////////////////////////End of configuration UI////////////////////////////////////////////////////
/////////////////////////////////Start of Specification UI//////////////////////////////////////////////////
/** Output the specification header section.
* This method is called in the head section of a job page which has selected a repository connection of the
* current type. Its purpose is to add the required tabs to the list, and to output any javascript methods
* that might be needed by the job editing HTML.
* The connector will be connected before this method can be called.
*@param out is the output to which any HTML should be sent.
*@param locale is the locale the output is preferred to be in.
*@param ds is the current document specification for this job.
*@param connectionSequenceNumber is the unique number of this connection within the job.
*@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector.
*/
@Override
public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds,
int connectionSequenceNumber, List<String> tabsArray)
throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
// Add the tabs
tabsArray.add(Messages.getString(locale, "EmailConnector.Message"));
Messages.outputResourceWithVelocity(out, locale, "SpecificationHeader.js", paramMap);
}
/** Output the specification body section.
* This method is called in the body section of a job page which has selected a repository connection of the
* current type. Its purpose is to present the required form elements for editing.
* The coder can presume that the HTML that is output from this configuration will be within appropriate
* <html>, <body>, and <form> tags. The name of the form is always "editjob".
* The connector will be connected before this method can be called.
*@param out is the output to which any HTML should be sent.
*@param locale is the locale the output is preferred to be in.
*@param ds is the current document specification for this job.
*@param connectionSequenceNumber is the unique number of this connection within the job.
*@param actualSequenceNumber is the connection within the job that has currently been selected.
*@param tabName is the current tab name. (actualSequenceNumber, tabName) form a unique tuple within
* the job.
*/
@Override
public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds,
int connectionSequenceNumber, int actualSequenceNumber, String tabName)
throws ManifoldCFException, IOException {
outputMessageTab(out, locale, ds, tabName, connectionSequenceNumber, actualSequenceNumber);
}
/**
* Take care of "Message" tab.
*/
protected void outputMessageTab(IHTTPOutput out, Locale locale,
Specification ds, String tabName, int connectionSequenceNumber, int actualSequenceNumber)
throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("TabName", tabName);
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
paramMap.put("SelectedNum", Integer.toString(actualSequenceNumber));
fillInMessageTab(paramMap, ds);
Messages.outputResourceWithVelocity(out, locale, "Specification_Message.html", paramMap);
}
/**
* Fill in Velocity context for Metadata tab.
*/
protected static void fillInMessageTab(Map<String, Object> paramMap,
Specification ds) {
// Preload default values, for backwards compatibility
String toValue = "";
String fromValue = "";
String subjectValue = "";
String bodyValue = "";
for (int i = 0; i < ds.getChildCount(); i++) {
SpecificationNode sn = ds.getChild(i);
if (sn.getType().equals(EmailConfig.NODE_TO)) {
toValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_FROM)) {
fromValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_SUBJECT)) {
subjectValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_BODY)) {
bodyValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
}
}
// If ANY of the above are non-empty, we create a new dummy record
if (toValue.length() > 0) {
// Add the dummy records
addRecord(paramMap, EmailConfig.NODE_FINISHED, toValue, fromValue, subjectValue, bodyValue);
addRecord(paramMap, EmailConfig.NODE_ERRORABORTED, toValue, fromValue, subjectValue, bodyValue);
addRecord(paramMap, EmailConfig.NODE_MANUALABORTED, toValue, fromValue, subjectValue, bodyValue);
addRecord(paramMap, EmailConfig.NODE_MANUALPAUSED, toValue, fromValue, subjectValue, bodyValue);
addRecord(paramMap, EmailConfig.NODE_SCHEDULEPAUSED, toValue, fromValue, subjectValue, bodyValue);
addRecord(paramMap, EmailConfig.NODE_RESTARTED, toValue, fromValue, subjectValue, bodyValue);
}
else
{
// Initialize all records with blanks
addRecord(paramMap, EmailConfig.NODE_FINISHED, "", "", "", "");
addRecord(paramMap, EmailConfig.NODE_ERRORABORTED, "", "", "", "");
addRecord(paramMap, EmailConfig.NODE_MANUALABORTED, "", "", "", "");
addRecord(paramMap, EmailConfig.NODE_MANUALPAUSED, "", "", "", "");
addRecord(paramMap, EmailConfig.NODE_SCHEDULEPAUSED, "", "", "", "");
addRecord(paramMap, EmailConfig.NODE_RESTARTED, "", "", "" ,"");
// Loop through nodes and pick them out that way
for (int i = 0; i < ds.getChildCount(); i++) {
SpecificationNode childNode = ds.getChild(i);
if (childNode.getType().equals(EmailConfig.NODE_FINISHED) ||
childNode.getType().equals(EmailConfig.NODE_ERRORABORTED) ||
childNode.getType().equals(EmailConfig.NODE_MANUALABORTED) ||
childNode.getType().equals(EmailConfig.NODE_MANUALPAUSED) ||
childNode.getType().equals(EmailConfig.NODE_SCHEDULEPAUSED) ||
childNode.getType().equals(EmailConfig.NODE_RESTARTED)) {
toValue = "";
fromValue = "";
subjectValue = "";
bodyValue = "";
for (int j = 0; j < childNode.getChildCount(); j++) {
SpecificationNode sn = childNode.getChild(j);
if (sn.getType().equals(EmailConfig.NODE_TO)) {
toValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_FROM)) {
fromValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_SUBJECT)) {
subjectValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
} else if (sn.getType().equals(EmailConfig.NODE_BODY)) {
bodyValue = sn.getAttributeValue(EmailConfig.ATTRIBUTE_VALUE);
}
}
addRecord(paramMap, childNode.getType(), toValue, fromValue, subjectValue, bodyValue);
}
}
}
}
protected static void addRecord(Map<String,Object> paramMap, String nodeType, String toValue, String fromValue, String subjectValue, String bodyValue) {
paramMap.put(nodeType+"_TO", toValue);
paramMap.put(nodeType+"_FROM", fromValue);
paramMap.put(nodeType+"_SUBJECT", subjectValue);
paramMap.put(nodeType+"_BODY", bodyValue);
}
/** Process a specification post.
* This method is called at the start of job's edit or view page, whenever there is a possibility that form
* data for a connection has been posted. Its purpose is to gather form information and modify the
* document specification accordingly. The name of the posted form is always "editjob".
* The connector will be connected before this method can be called.
*@param variableContext contains the post data, including binary file-upload information.
*@param locale is the locale the output is preferred to be in.
*@param ds is the current document specification for this job.
*@param connectionSequenceNumber is the unique number of this connection within the job.
*@return null if all is well, or a string error message if there is an error that should prevent saving of
* the job (and cause a redirection to an error page).
*/
@Override
public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds,
int connectionSequenceNumber)
throws ManifoldCFException {
return processMessageTab(variableContext, ds, connectionSequenceNumber);
}
protected String processMessageTab(IPostParameters variableContext, Specification ds,
int connectionSequenceNumber)
throws ManifoldCFException {
String seqPrefix = "s"+connectionSequenceNumber+"_";
// Remove legacy nodes always
removeNodes(ds, EmailConfig.NODE_TO);
removeNodes(ds, EmailConfig.NODE_FROM);
removeNodes(ds, EmailConfig.NODE_SUBJECT);
removeNodes(ds, EmailConfig.NODE_BODY);
// Gather all different kinds.
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_FINISHED);
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_ERRORABORTED);
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_MANUALABORTED);
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_MANUALPAUSED);
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_SCHEDULEPAUSED);
gatherRecord(ds, seqPrefix, variableContext, EmailConfig.NODE_RESTARTED);
return null;
}
protected static void gatherRecord(Specification ds, String seqPrefix, IPostParameters variableContext, String nodeType) {
removeNodes(ds, nodeType);
SpecificationNode sn = new SpecificationNode(nodeType);
String toString = variableContext.getParameter(seqPrefix + nodeType + "_to");
if (toString != null)
{
addNodeValue(sn, EmailConfig.NODE_TO, toString);
}
String fromString = variableContext.getParameter(seqPrefix + nodeType + "_from");
if (fromString != null)
{
addNodeValue(sn, EmailConfig.NODE_FROM, fromString);
}
String subjectString = variableContext.getParameter(seqPrefix + nodeType + "_subject");
if (subjectString != null)
{
addNodeValue(sn, EmailConfig.NODE_SUBJECT, subjectString);
}
String bodyString = variableContext.getParameter(seqPrefix + nodeType + "_body");
if (bodyString != null)
{
addNodeValue(sn, EmailConfig.NODE_BODY, bodyString);
}
ds.addChild(ds.getChildCount(),sn);
}
/** View specification.
* This method is called in the body section of a job's view page. Its purpose is to present the document
* specification information to the user. The coder can presume that the HTML that is output from
* this configuration will be within appropriate <html> and <body>tags.
* The connector will be connected before this method can be called.
*@param out is the output to which any HTML should be sent.
*@param locale is the locale the output is preferred to be in.
*@param ds is the current document specification for this job.
*@param connectionSequenceNumber is the unique number of this connection within the job.
*/
@Override
public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds,
int connectionSequenceNumber)
throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
fillInMessageTab(paramMap, ds);
Messages.outputResourceWithVelocity(out, locale, "SpecificationView.html", paramMap);
}
///////////////////////////////////////End of specification UI///////////////////////////////////////////////
protected static void addFindParameterNode(ConfigParams parameters, String findParameterName, String findParameterValue) {
ConfigNode cn = new ConfigNode(EmailConfig.NODE_PROPERTIES);
cn.setAttribute(EmailConfig.ATTRIBUTE_NAME, findParameterName);
cn.setAttribute(EmailConfig.ATTRIBUTE_VALUE, findParameterValue);
// Add to the end
parameters.addChild(parameters.getChildCount(), cn);
}
protected static void removeNodes(ConfigParams parameters, String nodeTypeName) {
int i = 0;
while (i < parameters.getChildCount()) {
ConfigNode cn = parameters.getChild(i);
if (cn.getType().equals(nodeTypeName))
parameters.removeChild(i);
else
i++;
}
}
protected static void removeNodes(Specification ds, String nodeTypeName) {
int i = 0;
while (i < ds.getChildCount()) {
SpecificationNode sn = ds.getChild(i);
if (sn.getType().equals(nodeTypeName))
ds.removeChild(i);
else
i++;
}
}
protected static void addNodeValue(SpecificationNode ds, String nodeType, String value)
{
SpecificationNode sn = new SpecificationNode(nodeType);
sn.setAttribute(EmailConfig.ATTRIBUTE_VALUE,value);
ds.addChild(ds.getChildCount(),sn);
}
/** Handle Messaging exceptions in a consistent global manner */
protected static void handleMessagingException(MessagingException e, String context)
throws ManifoldCFException, ServiceInterruption
{
Logging.connectors.error("Email: Error "+context+": "+e.getMessage(),e);
throw new ManifoldCFException("Error "+context+": "+e.getMessage(),e);
}
/** Class to set up connection.
*/
protected static class ConnectThread extends Thread
{
protected final String server;
protected final int port;
protected final String username;
protected final String password;
protected final Properties properties;
// Local session handle
protected EmailSession session = null;
protected Throwable exception = null;
public ConnectThread(String server, int port, String username, String password, Properties properties)
{
this.server = server;
this.port = port;
this.username = username;
this.password = password;
this.properties = properties;
setDaemon(true);
}
public void run()
{
try
{
session = new EmailSession(server, port, username, password, properties);
}
catch (Throwable e)
{
exception = e;
}
}
public EmailSession finishUp()
throws MessagingException, InterruptedException
{
try
{
join();
if (exception != null)
{
if (exception instanceof RuntimeException)
throw (RuntimeException)exception;
else if (exception instanceof Error)
throw (Error)exception;
else if (exception instanceof MessagingException)
throw (MessagingException)exception;
else
throw new RuntimeException("Unknown exception type: "+exception.getClass().getName()+": "+exception.getMessage(),exception);
}
return session;
} catch (InterruptedException e) {
this.interrupt();
throw e;
}
}
}
/** Class to close the session.
*/
protected static class CloseSessionThread extends Thread
{
protected final EmailSession session;
protected Throwable exception = null;
public CloseSessionThread(EmailSession session)
{
this.session = session;
setDaemon(true);
}
public void run()
{
try
{
session.close();
}
catch (Throwable e)
{
exception = e;
}
}
public void finishUp()
throws MessagingException, InterruptedException
{
try
{
join();
if (exception != null)
{
if (exception instanceof RuntimeException)
throw (RuntimeException)exception;
else if (exception instanceof Error)
throw (Error)exception;
else if (exception instanceof MessagingException)
throw (MessagingException)exception;
else
throw new RuntimeException("Unknown exception type: "+exception.getClass().getName()+": "+exception.getMessage(),exception);
}
} catch (InterruptedException e) {
this.interrupt();
throw e;
}
}
}
/** Class to check the connection.
*/
protected static class CheckConnectionThread extends Thread
{
protected final EmailSession session;
protected Throwable exception = null;
public CheckConnectionThread(EmailSession session)
{
this.session = session;
setDaemon(true);
}
public void run()
{
try
{
session.checkConnection();
}
catch (Throwable e)
{
exception = e;
}
}
public void finishUp()
throws MessagingException, InterruptedException
{
try
{
join();
if (exception != null)
{
if (exception instanceof RuntimeException)
throw (RuntimeException)exception;
else if (exception instanceof Error)
throw (Error)exception;
else if (exception instanceof MessagingException)
throw (MessagingException)exception;
else
throw new RuntimeException("Unknown exception type: "+exception.getClass().getName()+": "+exception.getMessage(),exception);
}
} catch (InterruptedException e) {
this.interrupt();
throw e;
}
}
}
/** Class to send email.
*/
protected static class SendThread extends Thread
{
protected final EmailSession session;
protected final List<String> to;
protected final String from;
protected final String subject;
protected final String body;
protected Throwable exception = null;
public SendThread(EmailSession session, List<String> to, String from, String subject, String body)
{
this.session = session;
this.to = to;
this.from = from;
this.subject = subject;
this.body = body;
setDaemon(true);
}
public void run()
{
try
{
session.send(to,from,subject,body);
}
catch (Throwable e)
{
exception = e;
}
}
public void finishUp()
throws MessagingException, InterruptedException
{
try
{
join();
if (exception != null)
{
if (exception instanceof RuntimeException)
throw (RuntimeException)exception;
else if (exception instanceof Error)
throw (Error)exception;
else if (exception instanceof MessagingException)
throw (MessagingException)exception;
else
throw new RuntimeException("Unknown exception type: "+exception.getClass().getName()+": "+exception.getMessage(),exception);
}
} catch (InterruptedException e) {
this.interrupt();
throw e;
}
}
}
} |
googleads/google-ads-java | 38,052 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/common/BudgetSimulationPoint.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/common/simulation.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.common;
/**
* <pre>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.BudgetSimulationPoint}
*/
public final class BudgetSimulationPoint extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.common.BudgetSimulationPoint)
BudgetSimulationPointOrBuilder {
private static final long serialVersionUID = 0L;
// Use BudgetSimulationPoint.newBuilder() to construct.
private BudgetSimulationPoint(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BudgetSimulationPoint() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BudgetSimulationPoint();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.SimulationProto.internal_static_google_ads_googleads_v19_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.SimulationProto.internal_static_google_ads_googleads_v19_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.BudgetSimulationPoint.class, com.google.ads.googleads.v19.common.BudgetSimulationPoint.Builder.class);
}
public static final int BUDGET_AMOUNT_MICROS_FIELD_NUMBER = 1;
private long budgetAmountMicros_ = 0L;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
public static final int REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER = 2;
private long requiredCpcBidCeilingMicros_ = 0L;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
public static final int BIDDABLE_CONVERSIONS_FIELD_NUMBER = 3;
private double biddableConversions_ = 0D;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
public static final int BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER = 4;
private double biddableConversionsValue_ = 0D;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
public static final int CLICKS_FIELD_NUMBER = 5;
private long clicks_ = 0L;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
public static final int COST_MICROS_FIELD_NUMBER = 6;
private long costMicros_ = 0L;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
public static final int IMPRESSIONS_FIELD_NUMBER = 7;
private long impressions_ = 0L;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
public static final int TOP_SLOT_IMPRESSIONS_FIELD_NUMBER = 8;
private long topSlotImpressions_ = 0L;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
public static final int INTERACTIONS_FIELD_NUMBER = 9;
private long interactions_ = 0L;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
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 (budgetAmountMicros_ != 0L) {
output.writeInt64(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
output.writeInt64(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
output.writeDouble(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
output.writeDouble(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
output.writeInt64(5, clicks_);
}
if (costMicros_ != 0L) {
output.writeInt64(6, costMicros_);
}
if (impressions_ != 0L) {
output.writeInt64(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
output.writeInt64(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
output.writeInt64(9, interactions_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (budgetAmountMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(5, clicks_);
}
if (costMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(6, costMicros_);
}
if (impressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(9, interactions_);
}
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.BudgetSimulationPoint)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.common.BudgetSimulationPoint other = (com.google.ads.googleads.v19.common.BudgetSimulationPoint) obj;
if (getBudgetAmountMicros()
!= other.getBudgetAmountMicros()) return false;
if (getRequiredCpcBidCeilingMicros()
!= other.getRequiredCpcBidCeilingMicros()) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversions())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversions())) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversionsValue())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversionsValue())) return false;
if (getClicks()
!= other.getClicks()) return false;
if (getCostMicros()
!= other.getCostMicros()) return false;
if (getImpressions()
!= other.getImpressions()) return false;
if (getTopSlotImpressions()
!= other.getTopSlotImpressions()) return false;
if (getInteractions()
!= other.getInteractions()) 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) + BUDGET_AMOUNT_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getBudgetAmountMicros());
hash = (37 * hash) + REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getRequiredCpcBidCeilingMicros());
hash = (37 * hash) + BIDDABLE_CONVERSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversions()));
hash = (37 * hash) + BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversionsValue()));
hash = (37 * hash) + CLICKS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getClicks());
hash = (37 * hash) + COST_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCostMicros());
hash = (37 * hash) + IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getImpressions());
hash = (37 * hash) + TOP_SLOT_IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getTopSlotImpressions());
hash = (37 * hash) + INTERACTIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getInteractions());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.common.BudgetSimulationPoint parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.BudgetSimulationPoint}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.common.BudgetSimulationPoint)
com.google.ads.googleads.v19.common.BudgetSimulationPointOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.SimulationProto.internal_static_google_ads_googleads_v19_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.SimulationProto.internal_static_google_ads_googleads_v19_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.BudgetSimulationPoint.class, com.google.ads.googleads.v19.common.BudgetSimulationPoint.Builder.class);
}
// Construct using com.google.ads.googleads.v19.common.BudgetSimulationPoint.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
budgetAmountMicros_ = 0L;
requiredCpcBidCeilingMicros_ = 0L;
biddableConversions_ = 0D;
biddableConversionsValue_ = 0D;
clicks_ = 0L;
costMicros_ = 0L;
impressions_ = 0L;
topSlotImpressions_ = 0L;
interactions_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.common.SimulationProto.internal_static_google_ads_googleads_v19_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.BudgetSimulationPoint getDefaultInstanceForType() {
return com.google.ads.googleads.v19.common.BudgetSimulationPoint.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.common.BudgetSimulationPoint build() {
com.google.ads.googleads.v19.common.BudgetSimulationPoint result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.BudgetSimulationPoint buildPartial() {
com.google.ads.googleads.v19.common.BudgetSimulationPoint result = new com.google.ads.googleads.v19.common.BudgetSimulationPoint(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.common.BudgetSimulationPoint result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.budgetAmountMicros_ = budgetAmountMicros_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requiredCpcBidCeilingMicros_ = requiredCpcBidCeilingMicros_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.biddableConversions_ = biddableConversions_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.biddableConversionsValue_ = biddableConversionsValue_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.clicks_ = clicks_;
}
if (((from_bitField0_ & 0x00000020) != 0)) {
result.costMicros_ = costMicros_;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.impressions_ = impressions_;
}
if (((from_bitField0_ & 0x00000080) != 0)) {
result.topSlotImpressions_ = topSlotImpressions_;
}
if (((from_bitField0_ & 0x00000100) != 0)) {
result.interactions_ = interactions_;
}
}
@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.BudgetSimulationPoint) {
return mergeFrom((com.google.ads.googleads.v19.common.BudgetSimulationPoint)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.common.BudgetSimulationPoint other) {
if (other == com.google.ads.googleads.v19.common.BudgetSimulationPoint.getDefaultInstance()) return this;
if (other.getBudgetAmountMicros() != 0L) {
setBudgetAmountMicros(other.getBudgetAmountMicros());
}
if (other.getRequiredCpcBidCeilingMicros() != 0L) {
setRequiredCpcBidCeilingMicros(other.getRequiredCpcBidCeilingMicros());
}
if (other.getBiddableConversions() != 0D) {
setBiddableConversions(other.getBiddableConversions());
}
if (other.getBiddableConversionsValue() != 0D) {
setBiddableConversionsValue(other.getBiddableConversionsValue());
}
if (other.getClicks() != 0L) {
setClicks(other.getClicks());
}
if (other.getCostMicros() != 0L) {
setCostMicros(other.getCostMicros());
}
if (other.getImpressions() != 0L) {
setImpressions(other.getImpressions());
}
if (other.getTopSlotImpressions() != 0L) {
setTopSlotImpressions(other.getTopSlotImpressions());
}
if (other.getInteractions() != 0L) {
setInteractions(other.getInteractions());
}
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: {
budgetAmountMicros_ = input.readInt64();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16: {
requiredCpcBidCeilingMicros_ = input.readInt64();
bitField0_ |= 0x00000002;
break;
} // case 16
case 25: {
biddableConversions_ = input.readDouble();
bitField0_ |= 0x00000004;
break;
} // case 25
case 33: {
biddableConversionsValue_ = input.readDouble();
bitField0_ |= 0x00000008;
break;
} // case 33
case 40: {
clicks_ = input.readInt64();
bitField0_ |= 0x00000010;
break;
} // case 40
case 48: {
costMicros_ = input.readInt64();
bitField0_ |= 0x00000020;
break;
} // case 48
case 56: {
impressions_ = input.readInt64();
bitField0_ |= 0x00000040;
break;
} // case 56
case 64: {
topSlotImpressions_ = input.readInt64();
bitField0_ |= 0x00000080;
break;
} // case 64
case 72: {
interactions_ = input.readInt64();
bitField0_ |= 0x00000100;
break;
} // case 72
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 long budgetAmountMicros_ ;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @param value The budgetAmountMicros to set.
* @return This builder for chaining.
*/
public Builder setBudgetAmountMicros(long value) {
budgetAmountMicros_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return This builder for chaining.
*/
public Builder clearBudgetAmountMicros() {
bitField0_ = (bitField0_ & ~0x00000001);
budgetAmountMicros_ = 0L;
onChanged();
return this;
}
private long requiredCpcBidCeilingMicros_ ;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @param value The requiredCpcBidCeilingMicros to set.
* @return This builder for chaining.
*/
public Builder setRequiredCpcBidCeilingMicros(long value) {
requiredCpcBidCeilingMicros_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return This builder for chaining.
*/
public Builder clearRequiredCpcBidCeilingMicros() {
bitField0_ = (bitField0_ & ~0x00000002);
requiredCpcBidCeilingMicros_ = 0L;
onChanged();
return this;
}
private double biddableConversions_ ;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @param value The biddableConversions to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversions(double value) {
biddableConversions_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversions() {
bitField0_ = (bitField0_ & ~0x00000004);
biddableConversions_ = 0D;
onChanged();
return this;
}
private double biddableConversionsValue_ ;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @param value The biddableConversionsValue to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversionsValue(double value) {
biddableConversionsValue_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversionsValue() {
bitField0_ = (bitField0_ & ~0x00000008);
biddableConversionsValue_ = 0D;
onChanged();
return this;
}
private long clicks_ ;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @param value The clicks to set.
* @return This builder for chaining.
*/
public Builder setClicks(long value) {
clicks_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return This builder for chaining.
*/
public Builder clearClicks() {
bitField0_ = (bitField0_ & ~0x00000010);
clicks_ = 0L;
onChanged();
return this;
}
private long costMicros_ ;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @param value The costMicros to set.
* @return This builder for chaining.
*/
public Builder setCostMicros(long value) {
costMicros_ = value;
bitField0_ |= 0x00000020;
onChanged();
return this;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return This builder for chaining.
*/
public Builder clearCostMicros() {
bitField0_ = (bitField0_ & ~0x00000020);
costMicros_ = 0L;
onChanged();
return this;
}
private long impressions_ ;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @param value The impressions to set.
* @return This builder for chaining.
*/
public Builder setImpressions(long value) {
impressions_ = value;
bitField0_ |= 0x00000040;
onChanged();
return this;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return This builder for chaining.
*/
public Builder clearImpressions() {
bitField0_ = (bitField0_ & ~0x00000040);
impressions_ = 0L;
onChanged();
return this;
}
private long topSlotImpressions_ ;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @param value The topSlotImpressions to set.
* @return This builder for chaining.
*/
public Builder setTopSlotImpressions(long value) {
topSlotImpressions_ = value;
bitField0_ |= 0x00000080;
onChanged();
return this;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return This builder for chaining.
*/
public Builder clearTopSlotImpressions() {
bitField0_ = (bitField0_ & ~0x00000080);
topSlotImpressions_ = 0L;
onChanged();
return this;
}
private long interactions_ ;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @param value The interactions to set.
* @return This builder for chaining.
*/
public Builder setInteractions(long value) {
interactions_ = value;
bitField0_ |= 0x00000100;
onChanged();
return this;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return This builder for chaining.
*/
public Builder clearInteractions() {
bitField0_ = (bitField0_ & ~0x00000100);
interactions_ = 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.v19.common.BudgetSimulationPoint)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.common.BudgetSimulationPoint)
private static final com.google.ads.googleads.v19.common.BudgetSimulationPoint DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.common.BudgetSimulationPoint();
}
public static com.google.ads.googleads.v19.common.BudgetSimulationPoint getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BudgetSimulationPoint>
PARSER = new com.google.protobuf.AbstractParser<BudgetSimulationPoint>() {
@java.lang.Override
public BudgetSimulationPoint 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<BudgetSimulationPoint> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BudgetSimulationPoint> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.BudgetSimulationPoint getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 38,052 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/common/BudgetSimulationPoint.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/common/simulation.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.common;
/**
* <pre>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.BudgetSimulationPoint}
*/
public final class BudgetSimulationPoint extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.common.BudgetSimulationPoint)
BudgetSimulationPointOrBuilder {
private static final long serialVersionUID = 0L;
// Use BudgetSimulationPoint.newBuilder() to construct.
private BudgetSimulationPoint(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BudgetSimulationPoint() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BudgetSimulationPoint();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.SimulationProto.internal_static_google_ads_googleads_v20_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.SimulationProto.internal_static_google_ads_googleads_v20_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.BudgetSimulationPoint.class, com.google.ads.googleads.v20.common.BudgetSimulationPoint.Builder.class);
}
public static final int BUDGET_AMOUNT_MICROS_FIELD_NUMBER = 1;
private long budgetAmountMicros_ = 0L;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
public static final int REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER = 2;
private long requiredCpcBidCeilingMicros_ = 0L;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
public static final int BIDDABLE_CONVERSIONS_FIELD_NUMBER = 3;
private double biddableConversions_ = 0D;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
public static final int BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER = 4;
private double biddableConversionsValue_ = 0D;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
public static final int CLICKS_FIELD_NUMBER = 5;
private long clicks_ = 0L;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
public static final int COST_MICROS_FIELD_NUMBER = 6;
private long costMicros_ = 0L;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
public static final int IMPRESSIONS_FIELD_NUMBER = 7;
private long impressions_ = 0L;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
public static final int TOP_SLOT_IMPRESSIONS_FIELD_NUMBER = 8;
private long topSlotImpressions_ = 0L;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
public static final int INTERACTIONS_FIELD_NUMBER = 9;
private long interactions_ = 0L;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
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 (budgetAmountMicros_ != 0L) {
output.writeInt64(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
output.writeInt64(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
output.writeDouble(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
output.writeDouble(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
output.writeInt64(5, clicks_);
}
if (costMicros_ != 0L) {
output.writeInt64(6, costMicros_);
}
if (impressions_ != 0L) {
output.writeInt64(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
output.writeInt64(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
output.writeInt64(9, interactions_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (budgetAmountMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(5, clicks_);
}
if (costMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(6, costMicros_);
}
if (impressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(9, interactions_);
}
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.BudgetSimulationPoint)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.common.BudgetSimulationPoint other = (com.google.ads.googleads.v20.common.BudgetSimulationPoint) obj;
if (getBudgetAmountMicros()
!= other.getBudgetAmountMicros()) return false;
if (getRequiredCpcBidCeilingMicros()
!= other.getRequiredCpcBidCeilingMicros()) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversions())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversions())) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversionsValue())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversionsValue())) return false;
if (getClicks()
!= other.getClicks()) return false;
if (getCostMicros()
!= other.getCostMicros()) return false;
if (getImpressions()
!= other.getImpressions()) return false;
if (getTopSlotImpressions()
!= other.getTopSlotImpressions()) return false;
if (getInteractions()
!= other.getInteractions()) 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) + BUDGET_AMOUNT_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getBudgetAmountMicros());
hash = (37 * hash) + REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getRequiredCpcBidCeilingMicros());
hash = (37 * hash) + BIDDABLE_CONVERSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversions()));
hash = (37 * hash) + BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversionsValue()));
hash = (37 * hash) + CLICKS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getClicks());
hash = (37 * hash) + COST_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCostMicros());
hash = (37 * hash) + IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getImpressions());
hash = (37 * hash) + TOP_SLOT_IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getTopSlotImpressions());
hash = (37 * hash) + INTERACTIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getInteractions());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.common.BudgetSimulationPoint parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.BudgetSimulationPoint}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.common.BudgetSimulationPoint)
com.google.ads.googleads.v20.common.BudgetSimulationPointOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.SimulationProto.internal_static_google_ads_googleads_v20_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.SimulationProto.internal_static_google_ads_googleads_v20_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.BudgetSimulationPoint.class, com.google.ads.googleads.v20.common.BudgetSimulationPoint.Builder.class);
}
// Construct using com.google.ads.googleads.v20.common.BudgetSimulationPoint.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
budgetAmountMicros_ = 0L;
requiredCpcBidCeilingMicros_ = 0L;
biddableConversions_ = 0D;
biddableConversionsValue_ = 0D;
clicks_ = 0L;
costMicros_ = 0L;
impressions_ = 0L;
topSlotImpressions_ = 0L;
interactions_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.common.SimulationProto.internal_static_google_ads_googleads_v20_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.BudgetSimulationPoint getDefaultInstanceForType() {
return com.google.ads.googleads.v20.common.BudgetSimulationPoint.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.common.BudgetSimulationPoint build() {
com.google.ads.googleads.v20.common.BudgetSimulationPoint result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.BudgetSimulationPoint buildPartial() {
com.google.ads.googleads.v20.common.BudgetSimulationPoint result = new com.google.ads.googleads.v20.common.BudgetSimulationPoint(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.common.BudgetSimulationPoint result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.budgetAmountMicros_ = budgetAmountMicros_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requiredCpcBidCeilingMicros_ = requiredCpcBidCeilingMicros_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.biddableConversions_ = biddableConversions_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.biddableConversionsValue_ = biddableConversionsValue_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.clicks_ = clicks_;
}
if (((from_bitField0_ & 0x00000020) != 0)) {
result.costMicros_ = costMicros_;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.impressions_ = impressions_;
}
if (((from_bitField0_ & 0x00000080) != 0)) {
result.topSlotImpressions_ = topSlotImpressions_;
}
if (((from_bitField0_ & 0x00000100) != 0)) {
result.interactions_ = interactions_;
}
}
@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.BudgetSimulationPoint) {
return mergeFrom((com.google.ads.googleads.v20.common.BudgetSimulationPoint)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.common.BudgetSimulationPoint other) {
if (other == com.google.ads.googleads.v20.common.BudgetSimulationPoint.getDefaultInstance()) return this;
if (other.getBudgetAmountMicros() != 0L) {
setBudgetAmountMicros(other.getBudgetAmountMicros());
}
if (other.getRequiredCpcBidCeilingMicros() != 0L) {
setRequiredCpcBidCeilingMicros(other.getRequiredCpcBidCeilingMicros());
}
if (other.getBiddableConversions() != 0D) {
setBiddableConversions(other.getBiddableConversions());
}
if (other.getBiddableConversionsValue() != 0D) {
setBiddableConversionsValue(other.getBiddableConversionsValue());
}
if (other.getClicks() != 0L) {
setClicks(other.getClicks());
}
if (other.getCostMicros() != 0L) {
setCostMicros(other.getCostMicros());
}
if (other.getImpressions() != 0L) {
setImpressions(other.getImpressions());
}
if (other.getTopSlotImpressions() != 0L) {
setTopSlotImpressions(other.getTopSlotImpressions());
}
if (other.getInteractions() != 0L) {
setInteractions(other.getInteractions());
}
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: {
budgetAmountMicros_ = input.readInt64();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16: {
requiredCpcBidCeilingMicros_ = input.readInt64();
bitField0_ |= 0x00000002;
break;
} // case 16
case 25: {
biddableConversions_ = input.readDouble();
bitField0_ |= 0x00000004;
break;
} // case 25
case 33: {
biddableConversionsValue_ = input.readDouble();
bitField0_ |= 0x00000008;
break;
} // case 33
case 40: {
clicks_ = input.readInt64();
bitField0_ |= 0x00000010;
break;
} // case 40
case 48: {
costMicros_ = input.readInt64();
bitField0_ |= 0x00000020;
break;
} // case 48
case 56: {
impressions_ = input.readInt64();
bitField0_ |= 0x00000040;
break;
} // case 56
case 64: {
topSlotImpressions_ = input.readInt64();
bitField0_ |= 0x00000080;
break;
} // case 64
case 72: {
interactions_ = input.readInt64();
bitField0_ |= 0x00000100;
break;
} // case 72
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 long budgetAmountMicros_ ;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @param value The budgetAmountMicros to set.
* @return This builder for chaining.
*/
public Builder setBudgetAmountMicros(long value) {
budgetAmountMicros_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return This builder for chaining.
*/
public Builder clearBudgetAmountMicros() {
bitField0_ = (bitField0_ & ~0x00000001);
budgetAmountMicros_ = 0L;
onChanged();
return this;
}
private long requiredCpcBidCeilingMicros_ ;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @param value The requiredCpcBidCeilingMicros to set.
* @return This builder for chaining.
*/
public Builder setRequiredCpcBidCeilingMicros(long value) {
requiredCpcBidCeilingMicros_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return This builder for chaining.
*/
public Builder clearRequiredCpcBidCeilingMicros() {
bitField0_ = (bitField0_ & ~0x00000002);
requiredCpcBidCeilingMicros_ = 0L;
onChanged();
return this;
}
private double biddableConversions_ ;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @param value The biddableConversions to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversions(double value) {
biddableConversions_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversions() {
bitField0_ = (bitField0_ & ~0x00000004);
biddableConversions_ = 0D;
onChanged();
return this;
}
private double biddableConversionsValue_ ;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @param value The biddableConversionsValue to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversionsValue(double value) {
biddableConversionsValue_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversionsValue() {
bitField0_ = (bitField0_ & ~0x00000008);
biddableConversionsValue_ = 0D;
onChanged();
return this;
}
private long clicks_ ;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @param value The clicks to set.
* @return This builder for chaining.
*/
public Builder setClicks(long value) {
clicks_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return This builder for chaining.
*/
public Builder clearClicks() {
bitField0_ = (bitField0_ & ~0x00000010);
clicks_ = 0L;
onChanged();
return this;
}
private long costMicros_ ;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @param value The costMicros to set.
* @return This builder for chaining.
*/
public Builder setCostMicros(long value) {
costMicros_ = value;
bitField0_ |= 0x00000020;
onChanged();
return this;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return This builder for chaining.
*/
public Builder clearCostMicros() {
bitField0_ = (bitField0_ & ~0x00000020);
costMicros_ = 0L;
onChanged();
return this;
}
private long impressions_ ;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @param value The impressions to set.
* @return This builder for chaining.
*/
public Builder setImpressions(long value) {
impressions_ = value;
bitField0_ |= 0x00000040;
onChanged();
return this;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return This builder for chaining.
*/
public Builder clearImpressions() {
bitField0_ = (bitField0_ & ~0x00000040);
impressions_ = 0L;
onChanged();
return this;
}
private long topSlotImpressions_ ;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @param value The topSlotImpressions to set.
* @return This builder for chaining.
*/
public Builder setTopSlotImpressions(long value) {
topSlotImpressions_ = value;
bitField0_ |= 0x00000080;
onChanged();
return this;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return This builder for chaining.
*/
public Builder clearTopSlotImpressions() {
bitField0_ = (bitField0_ & ~0x00000080);
topSlotImpressions_ = 0L;
onChanged();
return this;
}
private long interactions_ ;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @param value The interactions to set.
* @return This builder for chaining.
*/
public Builder setInteractions(long value) {
interactions_ = value;
bitField0_ |= 0x00000100;
onChanged();
return this;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return This builder for chaining.
*/
public Builder clearInteractions() {
bitField0_ = (bitField0_ & ~0x00000100);
interactions_ = 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.v20.common.BudgetSimulationPoint)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.common.BudgetSimulationPoint)
private static final com.google.ads.googleads.v20.common.BudgetSimulationPoint DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.common.BudgetSimulationPoint();
}
public static com.google.ads.googleads.v20.common.BudgetSimulationPoint getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BudgetSimulationPoint>
PARSER = new com.google.protobuf.AbstractParser<BudgetSimulationPoint>() {
@java.lang.Override
public BudgetSimulationPoint 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<BudgetSimulationPoint> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BudgetSimulationPoint> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.BudgetSimulationPoint getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 38,052 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/common/BudgetSimulationPoint.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/common/simulation.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.common;
/**
* <pre>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.BudgetSimulationPoint}
*/
public final class BudgetSimulationPoint extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.common.BudgetSimulationPoint)
BudgetSimulationPointOrBuilder {
private static final long serialVersionUID = 0L;
// Use BudgetSimulationPoint.newBuilder() to construct.
private BudgetSimulationPoint(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BudgetSimulationPoint() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BudgetSimulationPoint();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.SimulationProto.internal_static_google_ads_googleads_v21_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.SimulationProto.internal_static_google_ads_googleads_v21_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.BudgetSimulationPoint.class, com.google.ads.googleads.v21.common.BudgetSimulationPoint.Builder.class);
}
public static final int BUDGET_AMOUNT_MICROS_FIELD_NUMBER = 1;
private long budgetAmountMicros_ = 0L;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
public static final int REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER = 2;
private long requiredCpcBidCeilingMicros_ = 0L;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
public static final int BIDDABLE_CONVERSIONS_FIELD_NUMBER = 3;
private double biddableConversions_ = 0D;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
public static final int BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER = 4;
private double biddableConversionsValue_ = 0D;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
public static final int CLICKS_FIELD_NUMBER = 5;
private long clicks_ = 0L;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
public static final int COST_MICROS_FIELD_NUMBER = 6;
private long costMicros_ = 0L;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
public static final int IMPRESSIONS_FIELD_NUMBER = 7;
private long impressions_ = 0L;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
public static final int TOP_SLOT_IMPRESSIONS_FIELD_NUMBER = 8;
private long topSlotImpressions_ = 0L;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
public static final int INTERACTIONS_FIELD_NUMBER = 9;
private long interactions_ = 0L;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
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 (budgetAmountMicros_ != 0L) {
output.writeInt64(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
output.writeInt64(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
output.writeDouble(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
output.writeDouble(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
output.writeInt64(5, clicks_);
}
if (costMicros_ != 0L) {
output.writeInt64(6, costMicros_);
}
if (impressions_ != 0L) {
output.writeInt64(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
output.writeInt64(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
output.writeInt64(9, interactions_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (budgetAmountMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(1, budgetAmountMicros_);
}
if (requiredCpcBidCeilingMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(2, requiredCpcBidCeilingMicros_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversions_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(3, biddableConversions_);
}
if (java.lang.Double.doubleToRawLongBits(biddableConversionsValue_) != 0) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(4, biddableConversionsValue_);
}
if (clicks_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(5, clicks_);
}
if (costMicros_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(6, costMicros_);
}
if (impressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(7, impressions_);
}
if (topSlotImpressions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(8, topSlotImpressions_);
}
if (interactions_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(9, interactions_);
}
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.BudgetSimulationPoint)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.common.BudgetSimulationPoint other = (com.google.ads.googleads.v21.common.BudgetSimulationPoint) obj;
if (getBudgetAmountMicros()
!= other.getBudgetAmountMicros()) return false;
if (getRequiredCpcBidCeilingMicros()
!= other.getRequiredCpcBidCeilingMicros()) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversions())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversions())) return false;
if (java.lang.Double.doubleToLongBits(getBiddableConversionsValue())
!= java.lang.Double.doubleToLongBits(
other.getBiddableConversionsValue())) return false;
if (getClicks()
!= other.getClicks()) return false;
if (getCostMicros()
!= other.getCostMicros()) return false;
if (getImpressions()
!= other.getImpressions()) return false;
if (getTopSlotImpressions()
!= other.getTopSlotImpressions()) return false;
if (getInteractions()
!= other.getInteractions()) 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) + BUDGET_AMOUNT_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getBudgetAmountMicros());
hash = (37 * hash) + REQUIRED_CPC_BID_CEILING_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getRequiredCpcBidCeilingMicros());
hash = (37 * hash) + BIDDABLE_CONVERSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversions()));
hash = (37 * hash) + BIDDABLE_CONVERSIONS_VALUE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getBiddableConversionsValue()));
hash = (37 * hash) + CLICKS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getClicks());
hash = (37 * hash) + COST_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCostMicros());
hash = (37 * hash) + IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getImpressions());
hash = (37 * hash) + TOP_SLOT_IMPRESSIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getTopSlotImpressions());
hash = (37 * hash) + INTERACTIONS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getInteractions());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.common.BudgetSimulationPoint parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.BudgetSimulationPoint 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.BudgetSimulationPoint parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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.BudgetSimulationPoint 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>
* Projected metrics for a specific budget amount.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.BudgetSimulationPoint}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.common.BudgetSimulationPoint)
com.google.ads.googleads.v21.common.BudgetSimulationPointOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.SimulationProto.internal_static_google_ads_googleads_v21_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.SimulationProto.internal_static_google_ads_googleads_v21_common_BudgetSimulationPoint_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.BudgetSimulationPoint.class, com.google.ads.googleads.v21.common.BudgetSimulationPoint.Builder.class);
}
// Construct using com.google.ads.googleads.v21.common.BudgetSimulationPoint.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
budgetAmountMicros_ = 0L;
requiredCpcBidCeilingMicros_ = 0L;
biddableConversions_ = 0D;
biddableConversionsValue_ = 0D;
clicks_ = 0L;
costMicros_ = 0L;
impressions_ = 0L;
topSlotImpressions_ = 0L;
interactions_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.common.SimulationProto.internal_static_google_ads_googleads_v21_common_BudgetSimulationPoint_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.BudgetSimulationPoint getDefaultInstanceForType() {
return com.google.ads.googleads.v21.common.BudgetSimulationPoint.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.common.BudgetSimulationPoint build() {
com.google.ads.googleads.v21.common.BudgetSimulationPoint result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.BudgetSimulationPoint buildPartial() {
com.google.ads.googleads.v21.common.BudgetSimulationPoint result = new com.google.ads.googleads.v21.common.BudgetSimulationPoint(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.common.BudgetSimulationPoint result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.budgetAmountMicros_ = budgetAmountMicros_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requiredCpcBidCeilingMicros_ = requiredCpcBidCeilingMicros_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.biddableConversions_ = biddableConversions_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.biddableConversionsValue_ = biddableConversionsValue_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.clicks_ = clicks_;
}
if (((from_bitField0_ & 0x00000020) != 0)) {
result.costMicros_ = costMicros_;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.impressions_ = impressions_;
}
if (((from_bitField0_ & 0x00000080) != 0)) {
result.topSlotImpressions_ = topSlotImpressions_;
}
if (((from_bitField0_ & 0x00000100) != 0)) {
result.interactions_ = interactions_;
}
}
@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.BudgetSimulationPoint) {
return mergeFrom((com.google.ads.googleads.v21.common.BudgetSimulationPoint)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.common.BudgetSimulationPoint other) {
if (other == com.google.ads.googleads.v21.common.BudgetSimulationPoint.getDefaultInstance()) return this;
if (other.getBudgetAmountMicros() != 0L) {
setBudgetAmountMicros(other.getBudgetAmountMicros());
}
if (other.getRequiredCpcBidCeilingMicros() != 0L) {
setRequiredCpcBidCeilingMicros(other.getRequiredCpcBidCeilingMicros());
}
if (other.getBiddableConversions() != 0D) {
setBiddableConversions(other.getBiddableConversions());
}
if (other.getBiddableConversionsValue() != 0D) {
setBiddableConversionsValue(other.getBiddableConversionsValue());
}
if (other.getClicks() != 0L) {
setClicks(other.getClicks());
}
if (other.getCostMicros() != 0L) {
setCostMicros(other.getCostMicros());
}
if (other.getImpressions() != 0L) {
setImpressions(other.getImpressions());
}
if (other.getTopSlotImpressions() != 0L) {
setTopSlotImpressions(other.getTopSlotImpressions());
}
if (other.getInteractions() != 0L) {
setInteractions(other.getInteractions());
}
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: {
budgetAmountMicros_ = input.readInt64();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16: {
requiredCpcBidCeilingMicros_ = input.readInt64();
bitField0_ |= 0x00000002;
break;
} // case 16
case 25: {
biddableConversions_ = input.readDouble();
bitField0_ |= 0x00000004;
break;
} // case 25
case 33: {
biddableConversionsValue_ = input.readDouble();
bitField0_ |= 0x00000008;
break;
} // case 33
case 40: {
clicks_ = input.readInt64();
bitField0_ |= 0x00000010;
break;
} // case 40
case 48: {
costMicros_ = input.readInt64();
bitField0_ |= 0x00000020;
break;
} // case 48
case 56: {
impressions_ = input.readInt64();
bitField0_ |= 0x00000040;
break;
} // case 56
case 64: {
topSlotImpressions_ = input.readInt64();
bitField0_ |= 0x00000080;
break;
} // case 64
case 72: {
interactions_ = input.readInt64();
bitField0_ |= 0x00000100;
break;
} // case 72
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 long budgetAmountMicros_ ;
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return The budgetAmountMicros.
*/
@java.lang.Override
public long getBudgetAmountMicros() {
return budgetAmountMicros_;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @param value The budgetAmountMicros to set.
* @return This builder for chaining.
*/
public Builder setBudgetAmountMicros(long value) {
budgetAmountMicros_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The simulated budget upon which projected metrics are based.
* </pre>
*
* <code>int64 budget_amount_micros = 1;</code>
* @return This builder for chaining.
*/
public Builder clearBudgetAmountMicros() {
bitField0_ = (bitField0_ & ~0x00000001);
budgetAmountMicros_ = 0L;
onChanged();
return this;
}
private long requiredCpcBidCeilingMicros_ ;
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return The requiredCpcBidCeilingMicros.
*/
@java.lang.Override
public long getRequiredCpcBidCeilingMicros() {
return requiredCpcBidCeilingMicros_;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @param value The requiredCpcBidCeilingMicros to set.
* @return This builder for chaining.
*/
public Builder setRequiredCpcBidCeilingMicros(long value) {
requiredCpcBidCeilingMicros_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Projected required daily cpc bid ceiling that the advertiser must set to
* realize this simulation, in micros of the advertiser currency.
* Only campaigns with the Target Spend bidding strategy support this field.
* </pre>
*
* <code>int64 required_cpc_bid_ceiling_micros = 2;</code>
* @return This builder for chaining.
*/
public Builder clearRequiredCpcBidCeilingMicros() {
bitField0_ = (bitField0_ & ~0x00000002);
requiredCpcBidCeilingMicros_ = 0L;
onChanged();
return this;
}
private double biddableConversions_ ;
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return The biddableConversions.
*/
@java.lang.Override
public double getBiddableConversions() {
return biddableConversions_;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @param value The biddableConversions to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversions(double value) {
biddableConversions_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Projected number of biddable conversions.
* </pre>
*
* <code>double biddable_conversions = 3;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversions() {
bitField0_ = (bitField0_ & ~0x00000004);
biddableConversions_ = 0D;
onChanged();
return this;
}
private double biddableConversionsValue_ ;
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return The biddableConversionsValue.
*/
@java.lang.Override
public double getBiddableConversionsValue() {
return biddableConversionsValue_;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @param value The biddableConversionsValue to set.
* @return This builder for chaining.
*/
public Builder setBiddableConversionsValue(double value) {
biddableConversionsValue_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Projected total value of biddable conversions.
* </pre>
*
* <code>double biddable_conversions_value = 4;</code>
* @return This builder for chaining.
*/
public Builder clearBiddableConversionsValue() {
bitField0_ = (bitField0_ & ~0x00000008);
biddableConversionsValue_ = 0D;
onChanged();
return this;
}
private long clicks_ ;
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return The clicks.
*/
@java.lang.Override
public long getClicks() {
return clicks_;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @param value The clicks to set.
* @return This builder for chaining.
*/
public Builder setClicks(long value) {
clicks_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
* <pre>
* Projected number of clicks.
* </pre>
*
* <code>int64 clicks = 5;</code>
* @return This builder for chaining.
*/
public Builder clearClicks() {
bitField0_ = (bitField0_ & ~0x00000010);
clicks_ = 0L;
onChanged();
return this;
}
private long costMicros_ ;
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return The costMicros.
*/
@java.lang.Override
public long getCostMicros() {
return costMicros_;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @param value The costMicros to set.
* @return This builder for chaining.
*/
public Builder setCostMicros(long value) {
costMicros_ = value;
bitField0_ |= 0x00000020;
onChanged();
return this;
}
/**
* <pre>
* Projected cost in micros.
* </pre>
*
* <code>int64 cost_micros = 6;</code>
* @return This builder for chaining.
*/
public Builder clearCostMicros() {
bitField0_ = (bitField0_ & ~0x00000020);
costMicros_ = 0L;
onChanged();
return this;
}
private long impressions_ ;
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return The impressions.
*/
@java.lang.Override
public long getImpressions() {
return impressions_;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @param value The impressions to set.
* @return This builder for chaining.
*/
public Builder setImpressions(long value) {
impressions_ = value;
bitField0_ |= 0x00000040;
onChanged();
return this;
}
/**
* <pre>
* Projected number of impressions.
* </pre>
*
* <code>int64 impressions = 7;</code>
* @return This builder for chaining.
*/
public Builder clearImpressions() {
bitField0_ = (bitField0_ & ~0x00000040);
impressions_ = 0L;
onChanged();
return this;
}
private long topSlotImpressions_ ;
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return The topSlotImpressions.
*/
@java.lang.Override
public long getTopSlotImpressions() {
return topSlotImpressions_;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @param value The topSlotImpressions to set.
* @return This builder for chaining.
*/
public Builder setTopSlotImpressions(long value) {
topSlotImpressions_ = value;
bitField0_ |= 0x00000080;
onChanged();
return this;
}
/**
* <pre>
* Projected number of top slot impressions.
* Only search advertising channel type supports this field.
* </pre>
*
* <code>int64 top_slot_impressions = 8;</code>
* @return This builder for chaining.
*/
public Builder clearTopSlotImpressions() {
bitField0_ = (bitField0_ & ~0x00000080);
topSlotImpressions_ = 0L;
onChanged();
return this;
}
private long interactions_ ;
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return The interactions.
*/
@java.lang.Override
public long getInteractions() {
return interactions_;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @param value The interactions to set.
* @return This builder for chaining.
*/
public Builder setInteractions(long value) {
interactions_ = value;
bitField0_ |= 0x00000100;
onChanged();
return this;
}
/**
* <pre>
* Projected number of interactions.
* Only discovery advertising channel type supports this field.
* </pre>
*
* <code>int64 interactions = 9;</code>
* @return This builder for chaining.
*/
public Builder clearInteractions() {
bitField0_ = (bitField0_ & ~0x00000100);
interactions_ = 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.common.BudgetSimulationPoint)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.common.BudgetSimulationPoint)
private static final com.google.ads.googleads.v21.common.BudgetSimulationPoint DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.common.BudgetSimulationPoint();
}
public static com.google.ads.googleads.v21.common.BudgetSimulationPoint getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BudgetSimulationPoint>
PARSER = new com.google.protobuf.AbstractParser<BudgetSimulationPoint>() {
@java.lang.Override
public BudgetSimulationPoint 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<BudgetSimulationPoint> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BudgetSimulationPoint> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.BudgetSimulationPoint getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,845 | java-edgenetwork/proto-google-cloud-edgenetwork-v1/src/main/java/com/google/cloud/edgenetwork/v1/ListRoutersRequest.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/edgenetwork/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.edgenetwork.v1;
/**
*
*
* <pre>
* Message for requesting list of Routers
* </pre>
*
* Protobuf type {@code google.cloud.edgenetwork.v1.ListRoutersRequest}
*/
public final class ListRoutersRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.edgenetwork.v1.ListRoutersRequest)
ListRoutersRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListRoutersRequest.newBuilder() to construct.
private ListRoutersRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListRoutersRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListRoutersRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListRoutersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListRoutersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgenetwork.v1.ListRoutersRequest.class,
com.google.cloud.edgenetwork.v1.ListRoutersRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.edgenetwork.v1.ListRoutersRequest)) {
return super.equals(obj);
}
com.google.cloud.edgenetwork.v1.ListRoutersRequest other =
(com.google.cloud.edgenetwork.v1.ListRoutersRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest 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.edgenetwork.v1.ListRoutersRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest 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.edgenetwork.v1.ListRoutersRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest 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.edgenetwork.v1.ListRoutersRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest 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.edgenetwork.v1.ListRoutersRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest 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.edgenetwork.v1.ListRoutersRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Routers
* </pre>
*
* Protobuf type {@code google.cloud.edgenetwork.v1.ListRoutersRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.edgenetwork.v1.ListRoutersRequest)
com.google.cloud.edgenetwork.v1.ListRoutersRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListRoutersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListRoutersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgenetwork.v1.ListRoutersRequest.class,
com.google.cloud.edgenetwork.v1.ListRoutersRequest.Builder.class);
}
// Construct using com.google.cloud.edgenetwork.v1.ListRoutersRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListRoutersRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListRoutersRequest getDefaultInstanceForType() {
return com.google.cloud.edgenetwork.v1.ListRoutersRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListRoutersRequest build() {
com.google.cloud.edgenetwork.v1.ListRoutersRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListRoutersRequest buildPartial() {
com.google.cloud.edgenetwork.v1.ListRoutersRequest result =
new com.google.cloud.edgenetwork.v1.ListRoutersRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.edgenetwork.v1.ListRoutersRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.edgenetwork.v1.ListRoutersRequest) {
return mergeFrom((com.google.cloud.edgenetwork.v1.ListRoutersRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.edgenetwork.v1.ListRoutersRequest other) {
if (other == com.google.cloud.edgenetwork.v1.ListRoutersRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListRoutersRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.edgenetwork.v1.ListRoutersRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.edgenetwork.v1.ListRoutersRequest)
private static final com.google.cloud.edgenetwork.v1.ListRoutersRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.edgenetwork.v1.ListRoutersRequest();
}
public static com.google.cloud.edgenetwork.v1.ListRoutersRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListRoutersRequest> PARSER =
new com.google.protobuf.AbstractParser<ListRoutersRequest>() {
@java.lang.Override
public ListRoutersRequest 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<ListRoutersRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListRoutersRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListRoutersRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,845 | java-edgenetwork/proto-google-cloud-edgenetwork-v1/src/main/java/com/google/cloud/edgenetwork/v1/ListSubnetsRequest.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/edgenetwork/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.edgenetwork.v1;
/**
*
*
* <pre>
* Message for requesting list of Subnets
* </pre>
*
* Protobuf type {@code google.cloud.edgenetwork.v1.ListSubnetsRequest}
*/
public final class ListSubnetsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.edgenetwork.v1.ListSubnetsRequest)
ListSubnetsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSubnetsRequest.newBuilder() to construct.
private ListSubnetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSubnetsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSubnetsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListSubnetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListSubnetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgenetwork.v1.ListSubnetsRequest.class,
com.google.cloud.edgenetwork.v1.ListSubnetsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.edgenetwork.v1.ListSubnetsRequest)) {
return super.equals(obj);
}
com.google.cloud.edgenetwork.v1.ListSubnetsRequest other =
(com.google.cloud.edgenetwork.v1.ListSubnetsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest 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.edgenetwork.v1.ListSubnetsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest 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.edgenetwork.v1.ListSubnetsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest 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.edgenetwork.v1.ListSubnetsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest 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.edgenetwork.v1.ListSubnetsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest 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.edgenetwork.v1.ListSubnetsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Subnets
* </pre>
*
* Protobuf type {@code google.cloud.edgenetwork.v1.ListSubnetsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.edgenetwork.v1.ListSubnetsRequest)
com.google.cloud.edgenetwork.v1.ListSubnetsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListSubnetsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListSubnetsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgenetwork.v1.ListSubnetsRequest.class,
com.google.cloud.edgenetwork.v1.ListSubnetsRequest.Builder.class);
}
// Construct using com.google.cloud.edgenetwork.v1.ListSubnetsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.edgenetwork.v1.ServiceProto
.internal_static_google_cloud_edgenetwork_v1_ListSubnetsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListSubnetsRequest getDefaultInstanceForType() {
return com.google.cloud.edgenetwork.v1.ListSubnetsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListSubnetsRequest build() {
com.google.cloud.edgenetwork.v1.ListSubnetsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListSubnetsRequest buildPartial() {
com.google.cloud.edgenetwork.v1.ListSubnetsRequest result =
new com.google.cloud.edgenetwork.v1.ListSubnetsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.edgenetwork.v1.ListSubnetsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.edgenetwork.v1.ListSubnetsRequest) {
return mergeFrom((com.google.cloud.edgenetwork.v1.ListSubnetsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.edgenetwork.v1.ListSubnetsRequest other) {
if (other == com.google.cloud.edgenetwork.v1.ListSubnetsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListSubnetsRequest
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.edgenetwork.v1.ListSubnetsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.edgenetwork.v1.ListSubnetsRequest)
private static final com.google.cloud.edgenetwork.v1.ListSubnetsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.edgenetwork.v1.ListSubnetsRequest();
}
public static com.google.cloud.edgenetwork.v1.ListSubnetsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSubnetsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListSubnetsRequest>() {
@java.lang.Override
public ListSubnetsRequest 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<ListSubnetsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSubnetsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.edgenetwork.v1.ListSubnetsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/gora | 38,048 | gora-mongodb/src/main/java/org/apache/gora/mongodb/store/MongoStore.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.gora.mongodb.store;
import com.google.common.base.Splitter;
import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.model.CountOptions;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.DeleteResult;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.util.Utf8;
import org.apache.commons.io.IOUtils;
import org.apache.gora.mongodb.filters.MongoFilterUtil;
import org.apache.gora.mongodb.query.MongoDBQuery;
import org.apache.gora.mongodb.query.MongoDBResult;
import org.apache.gora.mongodb.store.MongoMapping.DocumentFieldType;
import org.apache.gora.mongodb.utils.BSONDecorator;
import org.apache.gora.mongodb.utils.Utf8Codec;
import org.apache.gora.persistency.impl.BeanFactoryImpl;
import org.apache.gora.persistency.impl.DirtyListWrapper;
import org.apache.gora.persistency.impl.DirtyMapWrapper;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.query.PartitionQuery;
import org.apache.gora.query.Query;
import org.apache.gora.query.Result;
import org.apache.gora.query.impl.PartitionQueryImpl;
import org.apache.gora.store.DataStoreFactory;
import org.apache.gora.store.impl.DataStoreBase;
import org.apache.gora.util.AvroUtils;
import org.apache.gora.util.ClassLoadingUtils;
import org.apache.gora.util.GoraException;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.StreamSupport;
import static com.mongodb.AuthenticationMechanism.*;
import static com.mongodb.client.model.Filters.and;
/**
* Implementation of a MongoDB data store to be used by gora.
*
* @param <K>
* class to be used for the key
* @param <T>
* class to be persisted within the store
* @author Fabien Poulard fpoulard@dictanova.com
* @author Damien Raude-Morvan draudemorvan@dictanova.com
*/
public class MongoStore<K, T extends PersistentBase> extends
DataStoreBase<K, T> {
public static final Logger LOG = LoggerFactory.getLogger(MongoStore.class);
/**
* Default value for mapping file
*/
public static final String DEFAULT_MAPPING_FILE = "/gora-mongodb-mapping.xml";
/**
* Key at DataStore Properties (same as gora.properties) to hold a mapping loaded from memory, instead from filesystem like
* the one at PARSE_MAPPING_FILE_KEY. If this key is present, the mapping is loaded from the value instead of gora-mongodb-mapping.xml
*/
public static final String XML_MAPPING_DEFINITION = "gora.mapping" ;
/**
* MongoDB client
*/
private static ConcurrentHashMap<String, com.mongodb.client.MongoClient> mapsOfClients = new ConcurrentHashMap<>();
private MongoDatabase mongoClientDB;
private MongoCollection<Document> mongoClientColl;
/**
* Mapping definition for MongoDB
*/
private MongoMapping mapping;
private MongoFilterUtil<K, T> filterUtil;
public MongoStore() {
// Create a default mapping that will be overriden in initialize method
this.mapping = new MongoMapping();
}
/**
* Initialize the data store by reading the credentials, setting the client's
* properties up and reading the mapping file.
*/
public void initialize(final Class<K> keyClass,
final Class<T> pPersistentClass, final Properties properties) throws GoraException {
try {
LOG.debug("Initializing MongoDB store");
MongoStoreParameters parameters = MongoStoreParameters.load(properties, getConf());
super.initialize(keyClass, pPersistentClass, properties);
filterUtil = new MongoFilterUtil<>(getConf());
// Load the mapping
MongoMappingBuilder<K, T> builder = new MongoMappingBuilder<>(this);
LOG.debug("Initializing Mongo store with mapping {}.",
new Object[] { parameters.getMappingFile() });
InputStream mappingInputStream;
// If there is a mapping definition in the Properties, use it.
if (properties.containsKey(XML_MAPPING_DEFINITION)) {
if (LOG.isTraceEnabled()) LOG.trace(XML_MAPPING_DEFINITION + " = " + properties.getProperty(XML_MAPPING_DEFINITION));
mappingInputStream = IOUtils.toInputStream(properties.getProperty(XML_MAPPING_DEFINITION), (Charset)null);
}
// Otherwise use the mapping file from parameters.
else {
String mappingFile = parameters.getMappingFile();
mappingInputStream = getClass().getResourceAsStream(mappingFile);
}
builder.fromInputStream(mappingInputStream);
mapping = builder.build();
// Prepare MongoDB connection
mongoClientDB = getDB(parameters);
mongoClientColl = mongoClientDB
.getCollection(mapping.getCollectionName());
LOG.info("Initialized Mongo store for database {} of {}.", new Object[] {
parameters.getDbname(), parameters.getServers() });
} catch (GoraException e) {
throw e;
} catch (IOException e) {
LOG.error("Error while initializing MongoDB store", e);
throw new GoraException(e);
}
}
/**
* Retrieve a client connected to the MongoDB server to be used.
*
* @param params This value should specify the host:port (at least one) for
* connecting to remote MongoDB.
* @return a {@link com.mongodb.client.MongoClient} instance connected to the server
*/
public static com.mongodb.client.MongoClient getClient(MongoStoreParameters params) {
// Utf8 serialization!
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(new Utf8Codec())
);
// Configure options
MongoClientSettings.Builder settings = MongoClientSettings.builder();
settings.codecRegistry(codecRegistry);
if (params.getReadPreference() != null) {
settings.readPreference(ReadPreference.valueOf(params.getReadPreference()));
}
if (params.getWriteConcern() != null) {
settings.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
}
// Build server address
List<ServerAddress> seeds = new ArrayList<>();
Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
for (String server : serversArray) {
Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
if (!paramsIterator.hasNext()) {
// No server, use default
seeds.add(new ServerAddress());
} else {
String host = paramsIterator.next();
if (paramsIterator.hasNext()) {
String port = paramsIterator.next();
seeds.add(new ServerAddress(host, Integer.parseInt(port)));
} else {
seeds.add(new ServerAddress(host));
}
}
}
settings.applyToClusterSettings(builder -> builder.hosts(seeds));
// If configuration contains a login + secret, try to authenticated with DB
if (params.getLogin() != null && params.getSecret() != null) {
MongoCredential credential = createCredential(params.getAuthenticationType(), params.getLogin(), params.getDbname(), params.getSecret());
settings.credential(credential);
}
return MongoClients.create(settings.build());
}
/**
* This method creates credentials according to the Authentication type.
*
* @param authenticationType authentication Type (Authentication Mechanism)
* @param username username
* @param database database
* @param password password
* @return Mongo Crendential
* @see <a href="http://api.mongodb.com/java/current/com/mongodb/AuthenticationMechanism.html">AuthenticationMechanism in MongoDB Java Driver</a>
*/
private static MongoCredential createCredential(String authenticationType, String username, String database, String password) {
MongoCredential credential = null;
if (PLAIN.getMechanismName().equals(authenticationType)) {
credential = MongoCredential.createPlainCredential(username, database, password.toCharArray());
} else if (SCRAM_SHA_1.getMechanismName().equals(authenticationType)) {
credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
} else if (SCRAM_SHA_256.getMechanismName().equals(authenticationType)) {
credential = MongoCredential.createScramSha256Credential(username, database, password.toCharArray());
} else if (GSSAPI.getMechanismName().equals(authenticationType)) {
credential = MongoCredential.createGSSAPICredential(username);
} else if (MONGODB_X509.getMechanismName().equals(authenticationType)) {
credential = MongoCredential.createMongoX509Credential(username);
} else {
credential = MongoCredential.createCredential(username, database, password.toCharArray());
}
return credential;
}
/**
* Get reference to Mongo DB, using credentials if not null.
*/
private MongoDatabase getDB(MongoStoreParameters parameters) throws UnknownHostException {
// Get reference to Mongo DB
if (!mapsOfClients.containsKey(parameters.getServers()))
mapsOfClients.put(parameters.getServers(), getClient(parameters));
return mapsOfClients.get(parameters.getServers()).getDatabase(parameters.getDbname());
}
public MongoMapping getMapping() {
return mapping;
}
/**
* Accessor to the name of the collection used.
*/
@Override
public String getSchemaName() {
return mapping.getCollectionName();
}
@Override
public String getSchemaName(final String mappingSchemaName,
final Class<?> persistentClass) {
return super.getSchemaName(mappingSchemaName, persistentClass);
}
/**
* Create a new collection in MongoDB if necessary.
*/
@Override
public void createSchema() throws GoraException {
if (mongoClientDB == null)
throw new GoraException(
"Impossible to create the schema as no database has been selected.");
if (schemaExists()) {
return;
}
try {
// If initialized create the collection
CreateCollectionOptions opts = new CreateCollectionOptions();
String name = mapping.getCollectionName();
mongoClientDB.createCollection(name, opts);
mongoClientColl = mongoClientDB.getCollection(name);
LOG.debug("Collection {} has been created for Mongo database {}.",
new Object[] {name, mongoClientDB.getName() });
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Drop the collection.
*/
@Override
public void deleteSchema() throws GoraException {
if (mongoClientColl == null)
throw new GoraException(
"Impossible to delete the schema as no schema is selected.");
try {
// If initialized, simply drop the collection
mongoClientColl.drop();
LOG.debug(
"Collection {} has been dropped.",
new Object[] { mongoClientColl.getNamespace().getFullName() });
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Check if the collection already exists or should be created.
*/
@Override
public boolean schemaExists() throws GoraException {
try {
MongoIterable<String> names = mongoClientDB.listCollectionNames();
String name = mapping.getCollectionName();
return StreamSupport.stream(names.spliterator(), false)
.anyMatch(name::equals);
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Ensure the data is synced to disk.
*/
@Override
public void flush() throws GoraException {
// no-op
}
/**
* Release the resources linked to this collection
*/
@Override
public void close() {
}
/**
* Retrieve an entry from the store with only selected fields.
*
* @param key
* identifier of the document in the database
* @param fields
* list of fields to be loaded from the database
*/
@Override
public T get(final K key, final String[] fields) throws GoraException {
try {
String[] dbFields = getFieldsToQuery(fields);
// Prepare the MongoDB query
Document q = new Document("_id", key);
Document proj = new Document();
for (String field : dbFields) {
String docf = mapping.getDocumentField(field);
if (docf != null) {
proj.put(docf, true);
}
}
// Execute the query
FindIterable<Document> res = mongoClientColl.find(q).projection(proj);
// Build the corresponding persistent
return newInstance(res.first(), dbFields);
} catch (Exception e) {
throw new GoraException(e);
}
}
@Override
public boolean exists(final K key) throws GoraException {
try {
// Prepare the MongoDB query
Document q = new Document("_id", key);
// Execute the query
long res = mongoClientColl.countDocuments(q);
return res > 0;
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Persist an object into the store.
*
* @param key
* identifier of the object in the store
* @param obj
* the object to be inserted
*/
@Override
public void put(final K key, final T obj) throws GoraException {
try {
// Save the object in the database
if (obj.isDirty()) {
performPut(key, obj);
} else {
LOG.info("Ignored putting object {} in the store as it is neither "
+ "new, neither dirty.", new Object[] { obj });
}
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Update a object that already exists in the store. The object must exist
* already or the update may fail.
*
* @param key
* identifier of the object in the store
* @param obj
* the object to be inserted
*/
private void performPut(final K key, final T obj) {
// Build the query to select the object to be updated
Document qSel = new Document("_id", key);
// Build the update query
Document qUpdate = new Document();
Document qUpdateSet = newUpdateSetInstance(obj);
if (qUpdateSet.size() > 0) {
qUpdate.put("$set", qUpdateSet);
}
Document qUpdateUnset = newUpdateUnsetInstance(obj);
if (qUpdateUnset.size() > 0) {
qUpdate.put("$unset", qUpdateUnset);
}
// Execute the update (if there is at least one $set ot $unset
if (!qUpdate.isEmpty()) {
mongoClientColl.updateOne(qSel, qUpdate, new UpdateOptions().upsert(true));
obj.clearDirty();
} else {
LOG.debug("No update to perform, skip {}", key);
}
}
@Override
public boolean delete(final K key) throws GoraException {
try {
Document removeKey = new Document("_id", key);
DeleteResult writeResult = mongoClientColl.deleteOne(removeKey);
return writeResult.getDeletedCount() > 0;
} catch (Exception e) {
throw new GoraException(e);
}
}
@Override
public long deleteByQuery(final Query<K, T> query) throws GoraException {
try {
// Build the actual MongoDB query
Bson q = MongoDBQuery.toDBQuery(query);
DeleteResult writeResult = mongoClientColl.deleteMany(q);
return writeResult.getDeletedCount();
} catch (Exception e) {
throw new GoraException(e);
}
}
/**
* Execute the query and return the result.
*/
@Override
public Result<K, T> execute(final Query<K, T> query) throws GoraException {
try {
String[] fields = getFieldsToQuery(query.getFields());
// Build the actual MongoDB query
Bson q = MongoDBQuery.toDBQuery(query);
Bson p = MongoDBQuery.toProjection(fields, mapping);
if (query.getFilter() != null) {
Optional<Bson> filter = filterUtil.setFilter(query.getFilter(), this);
if (!filter.isPresent()) {
// don't need local filter
query.setLocalFilterEnabled(false);
} else {
q = and(q, filter.get());
}
}
// Execute the query on the collection
FindIterable<Document> iterable = mongoClientColl.find(q).projection(p);
CountOptions countOptions = new CountOptions();
if (query.getLimit() > 0) {
iterable.limit((int) query.getLimit());
countOptions.limit((int) query.getLimit());
}
iterable.batchSize(100);
iterable.noCursorTimeout(true);
// Build the result
long size = mongoClientColl.countDocuments(q, countOptions);
return new MongoDBResult<>(this, query, iterable.cursor(), size);
} catch(Exception e) {
throw new GoraException(e);
}
}
/**
* Create a new {@link Query} to query the datastore.
*/
@Override
public Query<K, T> newQuery() {
MongoDBQuery<K, T> query = new MongoDBQuery<>(this);
query.setFields(getFieldsToQuery(null));
return query;
}
/**
* Partitions the given query and returns a list of PartitionQuerys, which
* will execute on local data.
*/
@Override
public List<PartitionQuery<K, T>> getPartitions(final Query<K, T> query)
throws IOException {
// FIXME: for now, there is only one partition as we do not handle
// MongoDB sharding configuration
List<PartitionQuery<K, T>> partitions = new ArrayList<>();
PartitionQueryImpl<K, T> partitionQuery = new PartitionQueryImpl<>(
query);
partitionQuery.setConf(getConf());
partitions.add(partitionQuery);
return partitions;
}
// //////////////////////////////////////////////////////// DESERIALIZATION
/**
* Build a new instance of the persisted class from the {@link Document}
* retrieved from the database.
*
* @param obj
* the {@link Document} that results from the query to the database
* @param fields
* the list of fields to be mapped to the persistence class instance
* @return a persistence class instance which content was deserialized from
* the {@link Document}
* @throws GoraException
*/
public T newInstance(final Document obj, final String[] fields) throws GoraException {
if (obj == null)
return null;
BSONDecorator easybson = new BSONDecorator(obj);
// Create new empty persistent bean instance
T persistent = newPersistent();
String[] dbFields = getFieldsToQuery(fields);
// Populate each field
for (String f : dbFields) {
// Check the field exists in the mapping and in the db
String docf = mapping.getDocumentField(f);
if (docf == null || !easybson.containsField(docf))
continue;
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
Field field = fieldMap.get(f);
Schema fieldSchema = field.schema();
LOG.debug(
"Load from DBObject (MAIN), field:{}, schemaType:{}, docField:{}, storeType:{}",
new Object[] { field.name(), fieldSchema.getType(), docf, storeType });
Object result = fromDocument(fieldSchema, storeType, field, docf,
easybson);
persistent.put(field.pos(), result);
}
persistent.clearDirty();
return persistent;
}
private Object fromDocument(final Schema fieldSchema,
final DocumentFieldType storeType, final Field field, final String docf,
final BSONDecorator easybson) throws GoraException {
Object result = null;
switch (fieldSchema.getType()) {
case MAP:
result = fromMongoMap(docf, fieldSchema, easybson, field);
break;
case ARRAY:
result = fromMongoList(docf, fieldSchema, easybson, field);
break;
case RECORD:
Document rec = easybson.getDBObject(docf);
if (rec == null) {
result = null;
break;
}
result = fromMongoRecord(fieldSchema, docf, rec);
break;
case BOOLEAN:
result = easybson.getBoolean(docf);
break;
case DOUBLE:
result = easybson.getDouble(docf);
break;
case FLOAT:
result = easybson.getDouble(docf).floatValue();
break;
case INT:
result = easybson.getInt(docf);
break;
case LONG:
result = easybson.getLong(docf);
break;
case STRING:
result = fromMongoString(storeType, docf, easybson);
break;
case ENUM:
result = AvroUtils.getEnumValue(fieldSchema, easybson.getUtf8String(docf)
.toString());
break;
case BYTES:
case FIXED:
result = easybson.getBytes(docf);
break;
case NULL:
result = null;
break;
case UNION:
result = fromMongoUnion(fieldSchema, storeType, field, docf, easybson);
break;
default:
LOG.warn("Unable to read {}", docf);
break;
}
return result;
}
private Object fromMongoUnion(final Schema fieldSchema,
final DocumentFieldType storeType, final Field field, final String docf,
final BSONDecorator easybson) throws GoraException {
Object result;// schema [type0, type1]
Type type0 = fieldSchema.getTypes().get(0).getType();
Type type1 = fieldSchema.getTypes().get(1).getType();
// Check if types are different and there's a "null", like ["null","type"]
// or ["type","null"]
if (!type0.equals(type1)
&& (type0.equals(Type.NULL) || type1.equals(Type.NULL))) {
Schema innerSchema = fieldSchema.getTypes().get(1);
LOG.debug(
"Load from DBObject (UNION), schemaType:{}, docField:{}, storeType:{}",
new Object[] { innerSchema.getType(), docf, storeType });
// Deserialize as if schema was ["type"]
result = fromDocument(innerSchema, storeType, field, docf, easybson);
} else {
throw new IllegalStateException(
"MongoStore doesn't support 3 types union field yet. Please update your mapping");
}
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object fromMongoRecord(final Schema fieldSchema, final String docf,
final Document rec) throws GoraException {
Object result;
BSONDecorator innerBson = new BSONDecorator(rec);
Class<?> clazz = null;
try {
clazz = ClassLoadingUtils.loadClass(fieldSchema.getFullName());
} catch (ClassNotFoundException e) {
}
PersistentBase record = (PersistentBase) new BeanFactoryImpl(keyClass, clazz).newPersistent();
for (Field recField : fieldSchema.getFields()) {
Schema innerSchema = recField.schema();
DocumentFieldType innerStoreType = mapping
.getDocumentFieldType(innerSchema.getName());
String innerDocField = mapping.getDocumentField(recField.name()) != null ? mapping
.getDocumentField(recField.name()) : recField.name();
String fieldPath = docf + "." + innerDocField;
LOG.debug(
"Load from DBObject (RECORD), field:{}, schemaType:{}, docField:{}, storeType:{}",
new Object[] { recField.name(), innerSchema.getType(), fieldPath,
innerStoreType });
record.put(
recField.pos(),
fromDocument(innerSchema, innerStoreType, recField, innerDocField,
innerBson));
}
result = record;
return result;
}
/* pp */ Object fromMongoList(final String docf, final Schema fieldSchema,
final BSONDecorator easybson, final Field f) throws GoraException {
List<Document> list = easybson.getDBList(docf);
List<Object> rlist = new ArrayList<>();
if (list == null) {
return new DirtyListWrapper(rlist);
}
for (Object item : list) {
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
Object o = fromDocument(fieldSchema.getElementType(), storeType, f,
"item", new BSONDecorator(new Document("item", item)));
rlist.add(o);
}
return new DirtyListWrapper<>(rlist);
}
/* pp */ Object fromMongoMap(final String docf, final Schema fieldSchema,
final BSONDecorator easybson, final Field f) throws GoraException {
Document map = easybson.getDBObject(docf);
Map<Utf8, Object> rmap = new HashMap<>();
if (map == null) {
return new DirtyMapWrapper(rmap);
}
for (Entry<String, Object> e : map.entrySet()) {
String mapKey = e.getKey();
String decodedMapKey = decodeFieldKey(mapKey);
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
Object o = fromDocument(fieldSchema.getValueType(), storeType, f, mapKey,
new BSONDecorator(map));
rmap.put(new Utf8(decodedMapKey), o);
}
return new DirtyMapWrapper<>(rmap);
}
private Object fromMongoString(final DocumentFieldType storeType,
final String docf, final BSONDecorator easybson) {
Object result;
if (storeType == DocumentFieldType.OBJECTID) {
// Try auto-conversion of BSON data to ObjectId
// It will work if data is stored as String or as ObjectId
Object bin = easybson.get(docf);
if (bin instanceof String) {
ObjectId id = new ObjectId((String) bin);
result = new Utf8(id.toString());
} else {
result = new Utf8(bin.toString());
}
} else if (storeType == DocumentFieldType.DATE) {
Object bin = easybson.get(docf);
if (bin instanceof Date) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.getDefault());
calendar.setTime((Date) bin);
result = new Utf8(DatatypeConverter.printDateTime(calendar));
} else {
result = new Utf8(bin.toString());
}
} else {
result = easybson.getUtf8String(docf);
}
return result;
}
// ////////////////////////////////////////////////////////// SERIALIZATION
/**
* Build a new instance of {@link Document} from the persistence class
* instance in parameter. Limit the {@link Document} to the fields that are
* dirty and not null, that is the fields that will need to be updated in the
* store.
*
* @param persistent
* a persistence class instance which content is to be serialized as
* a {@link Document} for use as parameter of a $set operator
* @return a {@link Document} which content corresponds to the fields that
* have to be updated... and formatted to be passed in parameter of a
* $set operator
*/
private Document newUpdateSetInstance(final T persistent) {
Document result = new Document();
for (Field f : persistent.getSchema().getFields()) {
if (persistent.isDirty(f.pos()) && (persistent.get(f.pos()) != null)) {
String docf = mapping.getDocumentField(f.name());
Object value = persistent.get(f.pos());
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
LOG.debug(
"Transform value to DBObject (MAIN), docField:{}, schemaType:{}, storeType:{}",
new Object[] { docf, f.schema().getType(), storeType });
Object o = toDocument(docf, f.schema(), f.schema().getType(),
storeType, value);
result.put(docf, o);
}
}
return result;
}
/**
* Build a new instance of {@link Document} from the persistence class
* instance in parameter. Limit the {@link Document} to the fields that are
* dirty and null, that is the fields that will need to be updated in the
* store by being removed.
*
* @param persistent
* a persistence class instance which content is to be serialized as
* a {@link Document} for use as parameter of a $set operator
* @return a {@link Document} which content corresponds to the fields that
* have to be updated... and formated to be passed in parameter of a
* $unset operator
*/
private Document newUpdateUnsetInstance(final T persistent) {
Document result = new Document();
for (Field f : persistent.getSchema().getFields()) {
if (persistent.isDirty(f.pos()) && (persistent.get(f.pos()) == null)) {
String docf = mapping.getDocumentField(f.name());
Object value = persistent.get(f.pos());
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
LOG.debug(
"Transform value to DBObject (MAIN), docField:{}, schemaType:{}, storeType:{}",
new Object[] { docf, f.schema().getType(), storeType });
Object o = toDocument(docf, f.schema(), f.schema().getType(),
storeType, value);
result.put(docf, o);
}
}
return result;
}
@SuppressWarnings("unchecked")
private Object toDocument(final String docf, final Schema fieldSchema,
final Type fieldType, final DocumentFieldType storeType,
final Object value) {
Object result = null;
switch (fieldType) {
case MAP:
if (storeType != null && storeType != DocumentFieldType.DOCUMENT) {
throw new IllegalStateException(
"Field "
+ fieldSchema.getType()
+ ": to store a Gora 'map', target Mongo mapping have to be of 'document' type");
}
Schema valueSchema = fieldSchema.getValueType();
result = mapToMongo(docf, (Map<CharSequence, ?>) value, valueSchema,
valueSchema.getType());
break;
case ARRAY:
if (storeType != null && storeType != DocumentFieldType.LIST) {
throw new IllegalStateException(
"Field "
+ fieldSchema.getType()
+ ": To store a Gora 'array', target Mongo mapping have to be of 'list' type");
}
Schema elementSchema = fieldSchema.getElementType();
result = listToMongo(docf, (List<?>) value, elementSchema,
elementSchema.getType());
break;
case BYTES:
if (value != null) {
result = ((ByteBuffer) value).array();
}
break;
case INT:
case LONG:
case FLOAT:
case DOUBLE:
case BOOLEAN:
result = value;
break;
case STRING:
result = stringToMongo(fieldSchema, storeType, value);
break;
case ENUM:
if (value != null)
result = value.toString();
break;
case RECORD:
if (value == null)
break;
result = recordToMongo(docf, fieldSchema, value);
break;
case UNION:
result = unionToMongo(docf, fieldSchema, storeType, value);
break;
case FIXED:
result = value;
break;
default:
LOG.error("Unknown field type: {}", fieldSchema.getType());
break;
}
return result;
}
private Object unionToMongo(final String docf, final Schema fieldSchema,
final DocumentFieldType storeType, final Object value) {
Object result;// schema [type0, type1]
Type type0 = fieldSchema.getTypes().get(0).getType();
Type type1 = fieldSchema.getTypes().get(1).getType();
// Check if types are different and there's a "null", like ["null","type"]
// or ["type","null"]
if (!type0.equals(type1)
&& (type0.equals(Type.NULL) || type1.equals(Type.NULL))) {
Schema innerSchema = fieldSchema.getTypes().get(1);
LOG.debug(
"Transform value to DBObject (UNION), schemaType:{}, type1:{}, storeType:{}",
new Object[] { innerSchema.getType(), type1, storeType });
// Deserialize as if schema was ["type"]
result = toDocument(docf, innerSchema, type1, storeType, value);
} else {
throw new IllegalStateException(
"MongoStore doesn't support 3 types union field yet. Please update your mapping");
}
return result;
}
private Document recordToMongo(final String docf,
final Schema fieldSchema, final Object value) {
Document record = new Document();
for (Field member : fieldSchema.getFields()) {
Object innerValue = ((PersistentBase) value).get(member.pos());
String innerDoc = mapping.getDocumentField(member.name());
Type innerType = member.schema().getType();
DocumentFieldType innerStoreType = mapping.getDocumentFieldType(innerDoc);
LOG.debug(
"Transform value to DBObject (RECORD), docField:{}, schemaType:{}, storeType:{}",
new Object[] { member.name(), member.schema().getType(),
innerStoreType });
record.put(
member.name(),
toDocument(docf, member.schema(), innerType, innerStoreType,
innerValue));
}
return record;
}
private Object stringToMongo(final Schema fieldSchema,
final DocumentFieldType storeType, final Object value) {
Object result = null;
if (storeType == DocumentFieldType.OBJECTID) {
if (value != null) {
ObjectId id;
try {
id = new ObjectId(value.toString());
} catch (IllegalArgumentException e1) {
// Unable to parse anything from Utf8 value, throw error
throw new IllegalStateException("Field " + fieldSchema.getType()
+ ": Invalid string: unable to convert to ObjectId");
}
result = id;
}
} else if (storeType == DocumentFieldType.DATE) {
if (value != null) {
// Try to parse date from Utf8 value
Calendar calendar = null;
try {
// Parse as date + time
calendar = DatatypeConverter.parseDateTime(value.toString());
} catch (IllegalArgumentException e1) {
try {
// Parse as date only
calendar = DatatypeConverter.parseDate(value.toString());
} catch (IllegalArgumentException e2) {
// No-op
}
}
if (calendar == null) {
// Unable to parse anything from Utf8 value, throw error
throw new IllegalStateException("Field " + fieldSchema.getType()
+ ": Invalid date format '" + value + "'");
}
result = calendar.getTime();
}
} else {
if (value != null) {
result = value.toString();
}
}
return result;
}
/**
* Convert a Java Map as used in Gora generated classes to a Map that can
* safely be serialized into MongoDB.
*
* @param value
* the Java Map that must be serialized into a MongoDB object
* @param fieldType
* type of the values within the map
* @return a {@link Document} version of the {@link Map} that can be
* safely serialized into MongoDB.
*/
private Document mapToMongo(final String docf,
final Map<CharSequence, ?> value, final Schema fieldSchema,
final Type fieldType) {
Document map = new Document();
// Handle null case
if (value == null)
return map;
// Handle regular cases
for (Entry<CharSequence, ?> e : value.entrySet()) {
String mapKey = e.getKey().toString();
String encodedMapKey = encodeFieldKey(mapKey);
Object mapValue = e.getValue();
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
Object result = toDocument(docf, fieldSchema, fieldType, storeType,
mapValue);
map.put(encodedMapKey, result);
}
return map;
}
/**
* Convert a Java {@link GenericArray} as used in Gora generated classes to a
* List that can safely be serialized into MongoDB.
*
* @param array
* the {@link GenericArray} to be serialized
* @param fieldType
* type of the elements within the array
* @return a {@link BasicDBList} version of the {@link GenericArray} that can
* be safely serialized into MongoDB.
*/
private BasicDBList listToMongo(final String docf, final Collection<?> array,
final Schema fieldSchema, final Type fieldType) {
BasicDBList list = new BasicDBList();
// Handle null case
if (array == null)
return list;
// Handle regular cases
for (Object item : array) {
DocumentFieldType storeType = mapping.getDocumentFieldType(docf);
Object result = toDocument(docf, fieldSchema, fieldType, storeType, item);
list.add(result);
}
return list;
}
// //////////////////////////////////////////////////////// CLEANUP
/**
* Ensure Key encoding -> dots replaced with middle dots
*
* @param key
* char with only dots.
* @return encoded string with "\u00B7" chars..
*/
public String encodeFieldKey(final String key) {
if (key == null) {
return null;
}
return key.replace(".", "\u00B7");
}
/**
* Ensure Key decoding -> middle dots replaced with dots
*
* @param key
* encoded string with "\u00B7" chars.
* @return Cleanup up char with only dots.
*/
public String decodeFieldKey(final String key) {
if (key == null) {
return null;
}
return key.replace("\u00B7", ".");
}
}
|
apache/grails-core | 38,273 | grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/transform/LineNumberTransform.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.grails.gsp.compiler.transform;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassCodeVisitorSupport;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.AttributeExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BitwiseNegationExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ClosureListExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.ElvisOperatorExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.FieldExpression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.MethodPointerExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.SpreadExpression;
import org.codehaus.groovy.ast.expr.SpreadMapExpression;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.UnaryMinusExpression;
import org.codehaus.groovy.ast.expr.UnaryPlusExpression;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.BytecodeExpression;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import org.codehaus.groovy.transform.TransformWithPriority;
import org.springframework.util.ReflectionUtils;
import org.apache.grails.common.compiler.GroovyTransformOrder;
/**
* Convert line number information to that based on the line number array passed
* into the line number array in the {@link LineNumber} annotation.
*
* @author Andrew Eisenberg
*/
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class LineNumberTransform implements ASTTransformation, TransformWithPriority {
// LOG statements commented out because they were causing
// compilation problems when used outside of grails
// static final Log LOG = LogFactory.getLog(LineNumberTransform)
public void visit(ASTNode[] nodes, SourceUnit source) {
List<ClassNode> classes = source.getAST().getClasses();
AnnotationNode annotation = null;
for (ClassNode clazz : classes) {
annotation = findAnnotation(clazz);
if (annotation != null) {
break;
}
}
if (annotation == null) {
return;
}
int[] array = extractLineNumberArray(annotation);
if (array != null) {
LineNumberVisitor visitor = new LineNumberVisitor(array);
for (ClassNode clazz : classes) {
visitor.visitClass(clazz);
}
}
String sourceName = extractSourceName(annotation);
if (sourceName != null) {
source.getAST().setDescription(sourceName);
// source.name = sourceName
Field field = ReflectionUtils.findField(SourceUnit.class, "name");
field.setAccessible(true);
ReflectionUtils.setField(field, source, sourceName);
}
}
String extractSourceName(AnnotationNode node) {
ConstantExpression newName = (ConstantExpression) node.getMember("sourceName");
return (String) newName.getValue();
}
AnnotationNode findAnnotation(ClassNode clazz) {
if (clazz != null) {
for (AnnotationNode node : clazz.getAnnotations()) {
if (node.getClassNode().getName().equals(LineNumber.class.getName())) {
// LOG.debug "Transforming in ${clazz.name}"
return node;
}
}
}
return null;
}
int[] extractLineNumberArray(AnnotationNode node) {
ListExpression lineNumberArray = (ListExpression) node.getMember("lines");
// make assumption that this is a simple array of constants
List<Integer> numbers = new ArrayList<>();
for (Expression e : lineNumberArray.getExpressions()) {
if (e instanceof ConstantExpression) {
numbers.add((Integer) ((ConstantExpression) e).getValue());
}
else {
numbers.add(-1);
}
}
// LOG.debug "We have transformed: ${numbers}"
if (numbers.isEmpty()) {
return null;
}
int[] array = new int[numbers.size()];
for (int i = 0, count = numbers.size(); i < count; i++) {
array[i] = numbers.get(i);
}
return array;
}
@Override
public int priority() {
return GroovyTransformOrder.GSP_LINE_ORDER;
}
class LineNumberVisitor extends ClassCodeVisitorSupport {
int[] lineNumbers;
LineNumberVisitor(int[] lineNumbers) {
this.lineNumbers = lineNumbers;
/*
if (LOG.isDebugEnabled()) {
String numbers = "Line numbers: ";
for (int number : lineNumbers) {
numbers += number + ", ";
}
LOG.debug numbers
}
*/
}
@Override
protected void visitStatement(Statement statement) {
// LOG.debug "Transforming statement '${statement}':"
if (statement.getLineNumber() >= 0 && statement.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${statement.lineNumber} to ${lineNumbers[statement.lineNumber]}"
statement.setLineNumber(lineNumbers[statement.getLineNumber() - 1]);
}
if (statement.getLastLineNumber() > 0 && statement.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${statement.lastLineNumber} to ${lineNumbers[statement.lastLineNumber]}"
statement.setLastLineNumber(lineNumbers[statement.getLastLineNumber() - 1]);
}
}
@Override
public void visitMethodCallExpression(MethodCallExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitMethodCallExpression(expression);
}
@Override
public void visitStaticMethodCallExpression(StaticMethodCallExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitStaticMethodCallExpression(expression);
}
@Override
public void visitConstructorCallExpression(ConstructorCallExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitConstructorCallExpression(expression);
}
@Override
public void visitBinaryExpression(BinaryExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitBinaryExpression(expression);
}
@Override
public void visitTernaryExpression(TernaryExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitTernaryExpression(expression);
}
@Override
public void visitShortTernaryExpression(ElvisOperatorExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitShortTernaryExpression(expression);
}
@Override
public void visitPostfixExpression(PostfixExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitPostfixExpression(expression);
}
@Override
public void visitPrefixExpression(PrefixExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitPrefixExpression(expression);
}
@Override
public void visitBooleanExpression(BooleanExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitBooleanExpression(expression);
}
@Override
public void visitNotExpression(NotExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitNotExpression(expression);
}
@Override
public void visitClosureExpression(ClosureExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitClosureExpression(expression);
}
@Override
public void visitTupleExpression(TupleExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitTupleExpression(expression);
}
@Override
public void visitListExpression(ListExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitListExpression(expression);
}
@Override
public void visitArrayExpression(ArrayExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitArrayExpression(expression);
}
@Override
public void visitMapExpression(MapExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitMapExpression(expression);
}
@Override
public void visitMapEntryExpression(MapEntryExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitMapEntryExpression(expression);
}
@Override
public void visitRangeExpression(RangeExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitRangeExpression(expression);
}
@Override
public void visitSpreadExpression(SpreadExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitSpreadExpression(expression);
}
@Override
public void visitSpreadMapExpression(SpreadMapExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitSpreadMapExpression(expression);
}
@Override
public void visitMethodPointerExpression(
MethodPointerExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitMethodPointerExpression(expression);
}
@Override
public void visitUnaryMinusExpression(UnaryMinusExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitUnaryMinusExpression(expression);
}
@Override
public void visitUnaryPlusExpression(UnaryPlusExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitUnaryPlusExpression(expression);
}
@Override
public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitBitwiseNegationExpression(expression);
}
@Override
public void visitCastExpression(CastExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitCastExpression(expression);
}
@Override
public void visitConstantExpression(ConstantExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitConstantExpression(expression);
}
@Override
public void visitClassExpression(ClassExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitClassExpression(expression);
}
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitDeclarationExpression(expression);
}
@Override
public void visitPropertyExpression(PropertyExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitPropertyExpression(expression);
}
@Override
public void visitAttributeExpression(AttributeExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitAttributeExpression(expression);
}
@Override
public void visitFieldExpression(FieldExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitFieldExpression(expression);
}
@Override
public void visitGStringExpression(GStringExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitGStringExpression(expression);
}
@Override
public void visitArgumentlistExpression(ArgumentListExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitArgumentlistExpression(expression);
}
@Override
public void visitClosureListExpression(ClosureListExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitClosureListExpression(expression);
}
@Override
public void visitBytecodeExpression(BytecodeExpression expression) {
// LOG.debug "Transforming expression '${expression}':"
if (expression.getLineNumber() >= 0 && expression.getLineNumber() < lineNumbers.length) {
// LOG.debug " start from ${expression.lineNumber} to ${lineNumbers[expression.lineNumber - 1]}"
expression.setLineNumber(lineNumbers[expression.getLineNumber() - 1]);
}
if (expression.getLastLineNumber() > 0 && expression.getLastLineNumber() < lineNumbers.length) {
// LOG.debug " end from ${expression.lastLineNumber} to ${lineNumbers[expression.lastLineNumber - 1]}"
expression.setLastLineNumber(lineNumbers[expression.getLastLineNumber() - 1]);
}
super.visitBytecodeExpression(expression);
}
@Override
protected SourceUnit getSourceUnit() {
return null;
}
}
}
|
apache/orc | 37,043 | java/tools/src/test/org/apache/orc/tools/TestFileDump.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.orc.tools;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DateColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.ListColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.MapColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.StructColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.io.BytesWritable;
import org.apache.orc.ColumnStatistics;
import org.apache.orc.CompressionKind;
import org.apache.orc.OrcConf;
import org.apache.orc.OrcFile;
import org.apache.orc.Reader;
import org.apache.orc.StripeStatistics;
import org.apache.orc.TestConf;
import org.apache.orc.TypeDescription;
import org.apache.orc.Writer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.orc.tools.FileDump.RECOVER_READ_SIZE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class TestFileDump implements TestConf {
Path workDir = new Path(System.getProperty("test.tmp.dir"));
FileSystem fs;
Path testFilePath;
@BeforeEach
public void openFileSystem () throws Exception {
conf.setFloat(OrcConf.STRIPE_SIZE_CHECKRATIO.getAttribute(), 0.0f);
fs = FileSystem.getLocal(conf);
testFilePath = new Path(workDir + File.separator + "TestFileDump.testDump.orc");
fs.delete(testFilePath, false);
}
static TypeDescription getMyRecordType() {
return TypeDescription.createStruct()
.addField("i", TypeDescription.createInt())
.addField("l", TypeDescription.createLong())
.addField("s", TypeDescription.createString());
}
static void appendMyRecord(VectorizedRowBatch batch,
int i,
long l,
String str) {
((LongColumnVector) batch.cols[0]).vector[batch.size] = i;
((LongColumnVector) batch.cols[1]).vector[batch.size] = l;
if (str == null) {
batch.cols[2].noNulls = false;
batch.cols[2].isNull[batch.size] = true;
} else {
((BytesColumnVector) batch.cols[2]).setVal(batch.size,
str.getBytes(StandardCharsets.UTF_8));
}
batch.size += 1;
}
static TypeDescription getAllTypesType() {
return TypeDescription.createStruct()
.addField("b", TypeDescription.createBoolean())
.addField("bt", TypeDescription.createByte())
.addField("s", TypeDescription.createShort())
.addField("i", TypeDescription.createInt())
.addField("l", TypeDescription.createLong())
.addField("f", TypeDescription.createFloat())
.addField("d", TypeDescription.createDouble())
.addField("de", TypeDescription.createDecimal())
.addField("t", TypeDescription.createTimestamp())
.addField("dt", TypeDescription.createDate())
.addField("str", TypeDescription.createString())
.addField("c", TypeDescription.createChar().withMaxLength(5))
.addField("vc", TypeDescription.createVarchar().withMaxLength(10))
.addField("m", TypeDescription.createMap(
TypeDescription.createString(),
TypeDescription.createString()))
.addField("a", TypeDescription.createList(TypeDescription.createInt()))
.addField("st", TypeDescription.createStruct()
.addField("i", TypeDescription.createInt())
.addField("s", TypeDescription.createString()));
}
static void appendAllTypes(VectorizedRowBatch batch,
boolean b,
byte bt,
short s,
int i,
long l,
float f,
double d,
HiveDecimalWritable de,
Timestamp t,
DateWritable dt,
String str,
String c,
String vc,
Map<String, String> m,
List<Integer> a,
int sti,
String sts) {
int row = batch.size++;
((LongColumnVector) batch.cols[0]).vector[row] = b ? 1 : 0;
((LongColumnVector) batch.cols[1]).vector[row] = bt;
((LongColumnVector) batch.cols[2]).vector[row] = s;
((LongColumnVector) batch.cols[3]).vector[row] = i;
((LongColumnVector) batch.cols[4]).vector[row] = l;
((DoubleColumnVector) batch.cols[5]).vector[row] = f;
((DoubleColumnVector) batch.cols[6]).vector[row] = d;
((DecimalColumnVector) batch.cols[7]).vector[row].set(de);
((TimestampColumnVector) batch.cols[8]).set(row, t);
((LongColumnVector) batch.cols[9]).vector[row] = dt.getDays();
((BytesColumnVector) batch.cols[10]).setVal(row, str.getBytes(StandardCharsets.UTF_8));
((BytesColumnVector) batch.cols[11]).setVal(row, c.getBytes(StandardCharsets.UTF_8));
((BytesColumnVector) batch.cols[12]).setVal(row, vc.getBytes(StandardCharsets.UTF_8));
MapColumnVector map = (MapColumnVector) batch.cols[13];
int offset = map.childCount;
map.offsets[row] = offset;
map.lengths[row] = m.size();
map.childCount += map.lengths[row];
for(Map.Entry<String, String> entry: m.entrySet()) {
((BytesColumnVector) map.keys).setVal(offset, entry.getKey().getBytes(StandardCharsets.UTF_8));
((BytesColumnVector) map.values).setVal(offset++,
entry.getValue().getBytes(StandardCharsets.UTF_8));
}
ListColumnVector list = (ListColumnVector) batch.cols[14];
offset = list.childCount;
list.offsets[row] = offset;
list.lengths[row] = a.size();
list.childCount += list.lengths[row];
for(int e=0; e < a.size(); ++e) {
((LongColumnVector) list.child).vector[offset + e] = a.get(e);
}
StructColumnVector struct = (StructColumnVector) batch.cols[15];
((LongColumnVector) struct.fields[0]).vector[row] = sti;
((BytesColumnVector) struct.fields[1]).setVal(row, sts.getBytes(StandardCharsets.UTF_8));
}
private static final Pattern ignoreTailPattern =
Pattern.compile("^(?<head>File Version|\"softwareVersion\"): .*");
private static final Pattern fileSizePattern =
Pattern.compile("^(\"fileLength\"|File length): (?<size>[0-9]+).*");
// Allow file size to be up to 100 bytes larger.
private static final int SIZE_SLOP = 100;
/**
* Preprocess the string for matching.
* If it matches the fileSizePattern, we return the file size as a Long.
* @param line the input line
* @return the processed line or a Long with the file size
*/
private static Object preprocessLine(String line) {
if (line == null) {
return line;
}
line = line.trim();
Matcher match = fileSizePattern.matcher(line);
if (match.matches()) {
return Long.parseLong(match.group("size"));
}
match = ignoreTailPattern.matcher(line);
if (match.matches()) {
return match.group("head");
}
return line;
}
/**
* Compare two files for equivalence.
* @param expected Loaded from the class path
* @param actual Loaded from the file system
*/
public static void checkOutput(String expected,
String actual) throws Exception {
BufferedReader eStream = Files.newBufferedReader(Paths.get(
TestJsonFileDump.getFileFromClasspath(expected)), StandardCharsets.UTF_8);
BufferedReader aStream = Files.newBufferedReader(Paths.get(actual), StandardCharsets.UTF_8);
Object expectedLine = preprocessLine(eStream.readLine());
final String[] filenames = {"Structure for", "\"fileName\":"};
while (expectedLine != null) {
Object actualLine = preprocessLine(aStream.readLine());
if (expectedLine instanceof Long && actualLine instanceof Long) {
long diff = (Long) actualLine - (Long) expectedLine;
assertTrue(diff < SIZE_SLOP,
"expected: " + expectedLine + ", actual: " + actualLine);
} else {
String line = (String)expectedLine;
if (!Arrays.stream(filenames).anyMatch(s -> line.startsWith(s))) { // Ignore file path
assertEquals(expectedLine, actualLine);
}
}
expectedLine = preprocessLine(eStream.readLine());
}
assertNull(eStream.readLine());
assertNull(aStream.readLine());
eStream.close();
aStream.close();
}
@Test
public void testDump() throws Exception {
TypeDescription schema = getMyRecordType();
conf.set(OrcConf.ENCODING_STRATEGY.getAttribute(), "COMPRESSION");
conf.set(OrcConf.DICTIONARY_IMPL.getAttribute(), "rbtree");
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema)
.compress(CompressionKind.ZLIB)
.stripeSize(100000)
.rowIndexStride(1000));
Random r1 = new Random(1);
String[] words = new String[]{"It", "was", "the", "best", "of", "times,",
"it", "was", "the", "worst", "of", "times,", "it", "was", "the", "age",
"of", "wisdom,", "it", "was", "the", "age", "of", "foolishness,", "it",
"was", "the", "epoch", "of", "belief,", "it", "was", "the", "epoch",
"of", "incredulity,", "it", "was", "the", "season", "of", "Light,",
"it", "was", "the", "season", "of", "Darkness,", "it", "was", "the",
"spring", "of", "hope,", "it", "was", "the", "winter", "of", "despair,",
"we", "had", "everything", "before", "us,", "we", "had", "nothing",
"before", "us,", "we", "were", "all", "going", "direct", "to",
"Heaven,", "we", "were", "all", "going", "direct", "the", "other",
"way"};
VectorizedRowBatch batch = schema.createRowBatch(1000);
for(int i=0; i < 21000; ++i) {
appendMyRecord(batch, r1.nextInt(), r1.nextLong(),
words[r1.nextInt(words.length)]);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size > 0) {
writer.addRowBatch(batch);
}
writer.addUserMetadata("hive.acid.key.index",
StandardCharsets.UTF_8.encode("1,1,1;2,3,5;"));
writer.addUserMetadata("some.user.property",
StandardCharsets.UTF_8.encode("foo#bar$baz&"));
writer.close();
assertEquals(2079000, writer.getRawDataSize());
assertEquals(21000, writer.getNumberOfRows());
PrintStream origOut = System.out;
String outputFilename = "orc-file-dump.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--rowindex=1,2,3"});
System.out.flush();
System.setOut(origOut);
checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
@Test
public void testDataDump() throws Exception {
TypeDescription schema = getAllTypesType();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema)
.stripeSize(100000)
.compress(CompressionKind.NONE)
.bufferSize(10000)
.rowIndexStride(1000));
VectorizedRowBatch batch = schema.createRowBatch(1000);
Map<String, String> m = new HashMap<String, String>(2);
m.put("k1", "v1");
appendAllTypes(batch,
true,
(byte) 10,
(short) 100,
1000,
10000L,
4.0f,
20.0,
new HiveDecimalWritable("4.2222"),
new Timestamp(format.parse("2014-11-25 18:09:24").getTime()),
new DateWritable(DateWritable.millisToDays(
format.parse("2014-11-25 00:00:00").getTime())),
"string",
"hello",
"hello",
m,
Arrays.asList(100, 200),
10, "foo");
m.clear();
m.put("k3", "v3");
appendAllTypes(
batch,
false,
(byte)20,
(short)200,
2000,
20000L,
8.0f,
40.0,
new HiveDecimalWritable("2.2222"),
new Timestamp(format.parse("2014-11-25 18:02:44").getTime()),
new DateWritable(DateWritable.millisToDays(
format.parse("2014-09-28 00:00:00").getTime())),
"abcd",
"world",
"world",
m,
Arrays.asList(200, 300),
20, "bar");
writer.addRowBatch(batch);
writer.close();
assertEquals(1564, writer.getRawDataSize());
assertEquals(2, writer.getNumberOfRows());
PrintStream origOut = System.out;
ByteArrayOutputStream myOut = new ByteArrayOutputStream();
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, "UTF-8"));
FileDump.main(new String[]{testFilePath.toString(), "-d"});
System.out.flush();
System.setOut(origOut);
String[] lines = myOut.toString(StandardCharsets.UTF_8.toString()).split("\n");
assertEquals("{\"b\":true,\"bt\":10,\"s\":100,\"i\":1000,\"l\":10000,\"f\":4.0,\"d\":20.0,\"de\":\"4.2222\",\"t\":\"2014-11-25 18:09:24.0\",\"dt\":\"2014-11-25\",\"str\":\"string\",\"c\":\"hello\",\"vc\":\"hello\",\"m\":[{\"_key\":\"k1\",\"_value\":\"v1\"}],\"a\":[100,200],\"st\":{\"i\":10,\"s\":\"foo\"}}", lines[0]);
assertEquals("{\"b\":false,\"bt\":20,\"s\":200,\"i\":2000,\"l\":20000,\"f\":8.0,\"d\":40.0,\"de\":\"2.2222\",\"t\":\"2014-11-25 18:02:44.0\",\"dt\":\"2014-09-28\",\"str\":\"abcd\",\"c\":\"world\",\"vc\":\"world\",\"m\":[{\"_key\":\"k3\",\"_value\":\"v3\"}],\"a\":[200,300],\"st\":{\"i\":20,\"s\":\"bar\"}}", lines[1]);
}
// Test that if the fraction of rows that have distinct strings is greater than the configured
// threshold dictionary encoding is turned off. If dictionary encoding is turned off the length
// of the dictionary stream for the column will be 0 in the ORC file dump.
@Test
public void testDictionaryThreshold() throws Exception {
TypeDescription schema = getMyRecordType();
conf.set(OrcConf.ENCODING_STRATEGY.getAttribute(), "COMPRESSION");
conf.setFloat(OrcConf.DICTIONARY_KEY_SIZE_THRESHOLD.getAttribute(), 0.49f);
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema)
.stripeSize(100000)
.compress(CompressionKind.ZLIB)
.rowIndexStride(1000)
.bufferSize(10000));
VectorizedRowBatch batch = schema.createRowBatch(1000);
Random r1 = new Random(1);
String[] words = new String[]{"It", "was", "the", "best", "of", "times,",
"it", "was", "the", "worst", "of", "times,", "it", "was", "the", "age",
"of", "wisdom,", "it", "was", "the", "age", "of", "foolishness,", "it",
"was", "the", "epoch", "of", "belief,", "it", "was", "the", "epoch",
"of", "incredulity,", "it", "was", "the", "season", "of", "Light,",
"it", "was", "the", "season", "of", "Darkness,", "it", "was", "the",
"spring", "of", "hope,", "it", "was", "the", "winter", "of", "despair,",
"we", "had", "everything", "before", "us,", "we", "had", "nothing",
"before", "us,", "we", "were", "all", "going", "direct", "to",
"Heaven,", "we", "were", "all", "going", "direct", "the", "other",
"way"};
int nextInt = 0;
for(int i=0; i < 21000; ++i) {
// Write out the same string twice, this guarantees the fraction of rows with
// distinct strings is 0.5
if (i % 2 == 0) {
nextInt = r1.nextInt(words.length);
// Append the value of i to the word, this guarantees when an index or word is repeated
// the actual string is unique.
words[nextInt] += "-" + i;
}
appendMyRecord(batch, r1.nextInt(), r1.nextLong(), words[nextInt]);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size != 0) {
writer.addRowBatch(batch);
}
writer.close();
PrintStream origOut = System.out;
String outputFilename = "orc-file-dump-dictionary-threshold.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--rowindex=1,2,3"});
System.out.flush();
System.setOut(origOut);
checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
@Test
public void testBloomFilter() throws Exception {
TypeDescription schema = getMyRecordType();
schema.setAttribute("test1", "value1");
schema.findSubtype("s")
.setAttribute("test2", "value2")
.setAttribute("test3", "value3");
conf.set(OrcConf.ENCODING_STRATEGY.getAttribute(), "COMPRESSION");
conf.set(OrcConf.DICTIONARY_IMPL.getAttribute(), "rbtree");
OrcFile.WriterOptions options = OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema)
.stripeSize(100000)
.compress(CompressionKind.ZLIB)
.bufferSize(10000)
.rowIndexStride(1000)
.bloomFilterColumns("S");
Writer writer = OrcFile.createWriter(testFilePath, options);
Random r1 = new Random(1);
String[] words = new String[]{"It", "was", "the", "best", "of", "times,",
"it", "was", "the", "worst", "of", "times,", "it", "was", "the", "age",
"of", "wisdom,", "it", "was", "the", "age", "of", "foolishness,", "it",
"was", "the", "epoch", "of", "belief,", "it", "was", "the", "epoch",
"of", "incredulity,", "it", "was", "the", "season", "of", "Light,",
"it", "was", "the", "season", "of", "Darkness,", "it", "was", "the",
"spring", "of", "hope,", "it", "was", "the", "winter", "of", "despair,",
"we", "had", "everything", "before", "us,", "we", "had", "nothing",
"before", "us,", "we", "were", "all", "going", "direct", "to",
"Heaven,", "we", "were", "all", "going", "direct", "the", "other",
"way"};
VectorizedRowBatch batch = schema.createRowBatch(1000);
for(int i=0; i < 21000; ++i) {
appendMyRecord(batch, r1.nextInt(), r1.nextLong(),
words[r1.nextInt(words.length)]);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size > 0) {
writer.addRowBatch(batch);
}
writer.close();
PrintStream origOut = System.out;
String outputFilename = "orc-file-dump-bloomfilter.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--rowindex=3"});
System.out.flush();
System.setOut(origOut);
checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
@Test
public void testBloomFilter2() throws Exception {
TypeDescription schema = getMyRecordType();
conf.set(OrcConf.ENCODING_STRATEGY.getAttribute(), "COMPRESSION");
conf.set(OrcConf.DICTIONARY_IMPL.getAttribute(), "rbtree");
OrcFile.WriterOptions options = OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema)
.stripeSize(100000)
.compress(CompressionKind.ZLIB)
.bufferSize(10000)
.rowIndexStride(1000)
.bloomFilterColumns("l,s")
.bloomFilterFpp(0.01)
.bloomFilterVersion(OrcFile.BloomFilterVersion.ORIGINAL);
VectorizedRowBatch batch = schema.createRowBatch(1000);
Writer writer = OrcFile.createWriter(testFilePath, options);
Random r1 = new Random(1);
String[] words = new String[]{"It", "was", "the", "best", "of", "times,",
"it", "was", "the", "worst", "of", "times,", "it", "was", "the", "age",
"of", "wisdom,", "it", "was", "the", "age", "of", "foolishness,", "it",
"was", "the", "epoch", "of", "belief,", "it", "was", "the", "epoch",
"of", "incredulity,", "it", "was", "the", "season", "of", "Light,",
"it", "was", "the", "season", "of", "Darkness,", "it", "was", "the",
"spring", "of", "hope,", "it", "was", "the", "winter", "of", "despair,",
"we", "had", "everything", "before", "us,", "we", "had", "nothing",
"before", "us,", "we", "were", "all", "going", "direct", "to",
"Heaven,", "we", "were", "all", "going", "direct", "the", "other",
"way"};
for(int i=0; i < 21000; ++i) {
appendMyRecord(batch, r1.nextInt(), r1.nextLong(),
words[r1.nextInt(words.length)]);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size > 0) {
writer.addRowBatch(batch);
}
writer.close();
PrintStream origOut = System.out;
String outputFilename = "orc-file-dump-bloomfilter2.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--rowindex=2"});
System.out.flush();
System.setOut(origOut);
checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
private static BytesWritable bytes(int... items) {
BytesWritable result = new BytesWritable();
result.setSize(items.length);
for (int i = 0; i < items.length; ++i) {
result.getBytes()[i] = (byte) items[i];
}
return result;
}
private void appendRow(VectorizedRowBatch batch, BytesWritable bytes,
String str) {
int row = batch.size++;
if (bytes == null) {
batch.cols[0].noNulls = false;
batch.cols[0].isNull[row] = true;
} else {
((BytesColumnVector) batch.cols[0]).setVal(row, bytes.getBytes(),
0, bytes.getLength());
}
if (str == null) {
batch.cols[1].noNulls = false;
batch.cols[1].isNull[row] = true;
} else {
((BytesColumnVector) batch.cols[1]).setVal(row, str.getBytes(StandardCharsets.UTF_8));
}
}
@Test
public void testHasNull() throws Exception {
TypeDescription schema =
TypeDescription.createStruct()
.addField("bytes1", TypeDescription.createBinary())
.addField("string1", TypeDescription.createString());
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.setSchema(schema)
.compress(CompressionKind.ZLIB)
.rowIndexStride(1000)
.stripeSize(10000)
.bufferSize(10000));
VectorizedRowBatch batch = schema.createRowBatch(5000);
// STRIPE 1
// RG1
for(int i=0; i<1000; i++) {
appendRow(batch, bytes(1, 2, 3), "RG1");
}
writer.addRowBatch(batch);
batch.reset();
// RG2
for(int i=0; i<1000; i++) {
appendRow(batch, bytes(1, 2, 3), null);
}
writer.addRowBatch(batch);
batch.reset();
// RG3
for(int i=0; i<1000; i++) {
appendRow(batch, bytes(1, 2, 3), "RG3");
}
writer.addRowBatch(batch);
batch.reset();
// RG4
for (int i = 0; i < 1000; i++) {
appendRow(batch, bytes(1,2,3), null);
}
writer.addRowBatch(batch);
batch.reset();
// RG5
for(int i=0; i<1000; i++) {
appendRow(batch, bytes(1, 2, 3), null);
}
writer.addRowBatch(batch);
batch.reset();
// STRIPE 2
for (int i = 0; i < 5000; i++) {
appendRow(batch, bytes(1,2,3), null);
}
writer.addRowBatch(batch);
batch.reset();
// STRIPE 3
for (int i = 0; i < 5000; i++) {
appendRow(batch, bytes(1,2,3), "STRIPE-3");
}
writer.addRowBatch(batch);
batch.reset();
// STRIPE 4
for (int i = 0; i < 5000; i++) {
appendRow(batch, bytes(1,2,3), null);
}
writer.addRowBatch(batch);
batch.reset();
writer.close();
Reader reader = OrcFile.createReader(testFilePath,
OrcFile.readerOptions(conf).filesystem(fs));
// check the file level stats
ColumnStatistics[] stats = reader.getStatistics();
assertEquals(20000, stats[0].getNumberOfValues());
assertEquals(20000, stats[1].getNumberOfValues());
assertEquals(7000, stats[2].getNumberOfValues());
assertFalse(stats[0].hasNull());
assertFalse(stats[1].hasNull());
assertTrue(stats[2].hasNull());
// check the stripe level stats
List<StripeStatistics> stripeStats = reader.getStripeStatistics();
// stripe 1 stats
StripeStatistics ss1 = stripeStats.get(0);
ColumnStatistics ss1_cs1 = ss1.getColumnStatistics()[0];
ColumnStatistics ss1_cs2 = ss1.getColumnStatistics()[1];
ColumnStatistics ss1_cs3 = ss1.getColumnStatistics()[2];
assertFalse(ss1_cs1.hasNull());
assertFalse(ss1_cs2.hasNull());
assertTrue(ss1_cs3.hasNull());
// stripe 2 stats
StripeStatistics ss2 = stripeStats.get(1);
ColumnStatistics ss2_cs1 = ss2.getColumnStatistics()[0];
ColumnStatistics ss2_cs2 = ss2.getColumnStatistics()[1];
ColumnStatistics ss2_cs3 = ss2.getColumnStatistics()[2];
assertFalse(ss2_cs1.hasNull());
assertFalse(ss2_cs2.hasNull());
assertTrue(ss2_cs3.hasNull());
// stripe 3 stats
StripeStatistics ss3 = stripeStats.get(2);
ColumnStatistics ss3_cs1 = ss3.getColumnStatistics()[0];
ColumnStatistics ss3_cs2 = ss3.getColumnStatistics()[1];
ColumnStatistics ss3_cs3 = ss3.getColumnStatistics()[2];
assertFalse(ss3_cs1.hasNull());
assertFalse(ss3_cs2.hasNull());
assertFalse(ss3_cs3.hasNull());
// stripe 4 stats
StripeStatistics ss4 = stripeStats.get(3);
ColumnStatistics ss4_cs1 = ss4.getColumnStatistics()[0];
ColumnStatistics ss4_cs2 = ss4.getColumnStatistics()[1];
ColumnStatistics ss4_cs3 = ss4.getColumnStatistics()[2];
assertFalse(ss4_cs1.hasNull());
assertFalse(ss4_cs2.hasNull());
assertTrue(ss4_cs3.hasNull());
// Test file dump
PrintStream origOut = System.out;
String outputFilename = "orc-file-has-null.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--rowindex=2"});
System.out.flush();
System.setOut(origOut);
// If called with an expression evaluating to false, the test will halt
// and be ignored.
assumeTrue(!System.getProperty("os.name").startsWith("Windows"));
TestFileDump.checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
@Test
public void testIndexOf() {
byte[] bytes = ("OO" + OrcFile.MAGIC).getBytes(StandardCharsets.UTF_8);
byte[] pattern = OrcFile.MAGIC.getBytes(StandardCharsets.UTF_8);
assertEquals(2, FileDump.indexOf(bytes, pattern, 1));
}
@Test
public void testRecover() throws Exception {
TypeDescription schema = getMyRecordType();
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema));
Random r1 = new Random(1);
String[] words = new String[]{"It", "was", "the", "best", "of", "times,",
"it", "was", "the", "worst", "of", "times,", "it", "was", "the", "age",
"of", "wisdom,", "it", "was", "the", "age", "of", "foolishness,", "it",
"was", "the", "epoch", "of", "belief,", "it", "was", "the", "epoch",
"of", "incredulity,", "it", "was", "the", "season", "of", "Light,",
"it", "was", "the", "season", "of", "Darkness,", "it", "was", "the",
"spring", "of", "hope,", "it", "was", "the", "winter", "of", "despair,",
"we", "had", "everything", "before", "us,", "we", "had", "nothing",
"before", "us,", "we", "were", "all", "going", "direct", "to",
"Heaven,", "we", "were", "all", "going", "direct", "the", "other",
"way"};
VectorizedRowBatch batch = schema.createRowBatch(1000);
for(int i=0; i < 21000; ++i) {
appendMyRecord(batch, r1.nextInt(), r1.nextLong(),
words[r1.nextInt(words.length)]);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
if (batch.size > 0) {
writer.addRowBatch(batch);
}
writer.close();
long fileSize = fs.getFileStatus(testFilePath).getLen();
String testFilePathStr = testFilePath.toUri().getPath();
String copyTestFilePathStr = Path.mergePaths(
workDir, Path.mergePaths(new Path(Path.SEPARATOR),
new Path("CopyTestFileDump.testDump.orc")))
.toUri().getPath();
String testCrcFilePathStr = Path.mergePaths(
workDir, Path.mergePaths(new Path(Path.SEPARATOR),
new Path(".TestFileDump.testDump.orc.crc")))
.toUri().getPath();
try {
Files.copy(Paths.get(testFilePathStr), Paths.get(copyTestFilePathStr));
// Append write data to make it a corrupt file
try (FileOutputStream output = new FileOutputStream(testFilePathStr, true)) {
output.write(new byte[1024]);
output.write(OrcFile.MAGIC.getBytes(StandardCharsets.UTF_8));
output.write(new byte[1024]);
output.flush();
}
// Clean up the crc file and append data to avoid checksum read exceptions
Files.delete(Paths.get(testCrcFilePathStr));
conf.setInt(RECOVER_READ_SIZE, (int) (fileSize - 2));
FileDump.main(conf, new String[]{"--recover", "--skip-dump",
testFilePath.toUri().getPath()});
assertTrue(contentEquals(testFilePathStr, copyTestFilePathStr));
} finally {
Files.delete(Paths.get(copyTestFilePathStr));
}
}
@Test
public void testDoubleNaNAndInfinite() throws Exception {
TypeDescription schema = TypeDescription.fromString("struct<x:double>");
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema));
VectorizedRowBatch batch = schema.createRowBatch();
DoubleColumnVector x = (DoubleColumnVector) batch.cols[0];
int row = batch.size++;
x.vector[row] = Double.NaN;
row = batch.size++;
x.vector[row] = Double.POSITIVE_INFINITY;
row = batch.size++;
x.vector[row] = 12.34D;
if (batch.size != 0) {
writer.addRowBatch(batch);
}
writer.close();
assertEquals(3, writer.getNumberOfRows());
PrintStream origOut = System.out;
ByteArrayOutputStream myOut = new ByteArrayOutputStream();
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8));
FileDump.main(new String[]{testFilePath.toString(), "-d"});
System.out.flush();
System.setOut(origOut);
String[] lines = myOut.toString(StandardCharsets.UTF_8).split("\n");
assertEquals("{\"x\":NaN}", lines[0]);
assertEquals("{\"x\":Infinity}", lines[1]);
assertEquals("{\"x\":12.34}", lines[2]);
}
@Test
public void testDumpColumnType() throws Exception {
TypeDescription schema =
TypeDescription.fromString("struct<a:boolean,b:tinyint,c:smallint,d:int,e:bigint," +
"f:float,g:double,h:string,i:date,j:timestamp,k:binary,l:decimal(20,5),m:varchar(5)," +
"n:char(5)>");
Writer writer = OrcFile.createWriter(testFilePath,
OrcFile.writerOptions(conf)
.fileSystem(fs)
.setSchema(schema));
VectorizedRowBatch batch = schema.createRowBatch();
LongColumnVector a = (LongColumnVector) batch.cols[0];
LongColumnVector b = (LongColumnVector) batch.cols[1];
LongColumnVector c = (LongColumnVector) batch.cols[2];
LongColumnVector d = (LongColumnVector) batch.cols[3];
LongColumnVector e = (LongColumnVector) batch.cols[4];
DoubleColumnVector f = (DoubleColumnVector) batch.cols[5];
DoubleColumnVector g = (DoubleColumnVector) batch.cols[6];
BytesColumnVector h = (BytesColumnVector) batch.cols[7];
DateColumnVector i = (DateColumnVector) batch.cols[8];
TimestampColumnVector j = (TimestampColumnVector) batch.cols[9];
BytesColumnVector k = (BytesColumnVector) batch.cols[10];
DecimalColumnVector l = (DecimalColumnVector) batch.cols[11];
BytesColumnVector m = (BytesColumnVector) batch.cols[12];
BytesColumnVector n = (BytesColumnVector) batch.cols[13];
for (int o = 0; o < VectorizedRowBatch.DEFAULT_SIZE * 2; o++) {
int row = batch.size++;
a.vector[row] = row % 2;
b.vector[row] = row % 128;
c.vector[row] = row;
d.vector[row] = row;
e.vector[row] = row * 10000000L;
f.vector[row] = row * 1.0f;
g.vector[row] = row * 1.0d;
byte[] bytes = String.valueOf(row).getBytes(StandardCharsets.UTF_8);
h.setRef(row, bytes, 0, bytes.length);
i.vector[row] = row;
j.time[row] = row * 1000L;
j.nanos[row] = row;
k.setRef(row, bytes, 0, bytes.length);
l.vector[row] = new HiveDecimalWritable(row);
m.setRef(row, bytes, 0, bytes.length);
bytes = String.valueOf(10000 - row).getBytes(StandardCharsets.UTF_8);
n.setRef(row, bytes, 0, bytes.length);
if (batch.size == batch.getMaxSize()) {
writer.addRowBatch(batch);
batch.reset();
}
}
writer.close();
assertEquals(VectorizedRowBatch.DEFAULT_SIZE * 2, writer.getNumberOfRows());
PrintStream origOut = System.out;
String outputFilename = "orc-file-dump-column-type.out";
FileOutputStream myOut = new FileOutputStream(workDir + File.separator + outputFilename);
// replace stdout and run command
System.setOut(new PrintStream(myOut, false, StandardCharsets.UTF_8.toString()));
FileDump.main(new String[]{testFilePath.toString(), "--column-type"});
System.out.flush();
System.setOut(origOut);
checkOutput(outputFilename, workDir + File.separator + outputFilename);
}
private static boolean contentEquals(String filePath, String otherFilePath) throws IOException {
try (InputStream is = new BufferedInputStream(new FileInputStream(filePath));
InputStream otherIs = new BufferedInputStream(new FileInputStream(otherFilePath))) {
int ch = is.read();
while (-1 != ch) {
int ch2 = otherIs.read();
if (ch != ch2) {
return false;
}
ch = is.read();
}
int ch2 = otherIs.read();
return ch2 == -1;
}
}
}
|
apache/ignite-3 | 37,769 | modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/prepare/ddl/DistributionZoneSqlToCommandConverterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.sql.engine.prepare.ddl;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static org.apache.ignite.internal.catalog.CatalogService.DEFAULT_STORAGE_PROFILE;
import static org.apache.ignite.internal.catalog.commands.CatalogUtils.INFINITE_TIMER_VALUE;
import static org.apache.ignite.internal.lang.IgniteStringFormatter.format;
import static org.apache.ignite.internal.testframework.IgniteTestUtils.assertThrows;
import static org.apache.ignite.internal.testframework.IgniteTestUtils.assertThrowsWithCode;
import static org.apache.ignite.lang.ErrorGroups.Sql.STMT_VALIDATION_ERR;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.ignite.internal.catalog.CatalogCommand;
import org.apache.ignite.internal.catalog.CatalogValidationException;
import org.apache.ignite.internal.catalog.commands.AlterZoneCommand;
import org.apache.ignite.internal.catalog.commands.AlterZoneSetDefaultCommand;
import org.apache.ignite.internal.catalog.commands.DropZoneCommand;
import org.apache.ignite.internal.catalog.commands.RenameZoneCommand;
import org.apache.ignite.internal.catalog.descriptors.CatalogStorageProfileDescriptor;
import org.apache.ignite.internal.catalog.descriptors.CatalogZoneDescriptor;
import org.apache.ignite.internal.catalog.descriptors.ConsistencyMode;
import org.apache.ignite.internal.catalog.storage.AlterZoneEntry;
import org.apache.ignite.internal.catalog.storage.DropZoneEntry;
import org.apache.ignite.internal.catalog.storage.NewZoneEntry;
import org.apache.ignite.internal.catalog.storage.SetDefaultZoneEntry;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalNode;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologyService;
import org.apache.ignite.internal.cluster.management.topology.api.LogicalTopologySnapshot;
import org.apache.ignite.internal.network.ClusterNodeImpl;
import org.apache.ignite.internal.partitiondistribution.DistributionAlgorithm;
import org.apache.ignite.network.NetworkAddress;
import org.apache.ignite.sql.SqlException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests the conversion of a sql zone definition to a command.
*/
@SuppressWarnings("ThrowableNotThrown")
public class DistributionZoneSqlToCommandConverterTest extends AbstractDdlSqlToCommandConverterTest {
private static final List<ZoneOptionEnum> NUMERIC_OPTIONS = List.of(
ZoneOptionEnum.PARTITIONS,
ZoneOptionEnum.REPLICAS,
ZoneOptionEnum.QUORUM_SIZE,
ZoneOptionEnum.DATA_NODES_AUTO_ADJUST_SCALE_UP,
ZoneOptionEnum.DATA_NODES_AUTO_ADJUST_SCALE_DOWN
);
private static final List<ZoneOptionEnum> STRING_OPTIONS = List.of(
ZoneOptionEnum.DISTRIBUTION_ALGORITHM,
ZoneOptionEnum.DATA_NODES_FILTER,
ZoneOptionEnum.CONSISTENCY_MODE
);
private static final String AIPERSIST_STORAGE_PROFILE = "segmented_aipersist";
private static final String ROCKSDB_STORAGE_PROFILE = "lru_rocks";
private static final List<String> NODE_DEFAULT_STORAGE_PROFILES = List.of(
DEFAULT_STORAGE_PROFILE,
AIPERSIST_STORAGE_PROFILE,
ROCKSDB_STORAGE_PROFILE
);
private LogicalTopologyService logicalTopologyService;
@BeforeEach
public void setUp() {
// Default mock
logicalTopologyService = mock(LogicalTopologyService.class);
LogicalTopologySnapshot defaultLogicalTopologySnapshot = new LogicalTopologySnapshot(
0,
IntStream.range(0, 2)
.mapToObj(nodeIdx -> createLocalNode(nodeIdx, NODE_DEFAULT_STORAGE_PROFILES))
.collect(Collectors.toList())
);
when(logicalTopologyService.localLogicalTopology()).thenReturn(defaultLogicalTopologySnapshot);
when(logicalTopologyService.logicalTopologyOnLeader()).thenReturn(completedFuture(defaultLogicalTopologySnapshot));
converter = new DdlSqlToCommandConverter(
new ClusterWideStorageProfileValidator(logicalTopologyService),
filter -> completedFuture(null)
);
assertThat(ZoneOptionEnum.values().length, is(NUMERIC_OPTIONS.size() + STRING_OPTIONS.size()));
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZone(boolean withPresent) throws SqlParseException {
CatalogCommand cmd = convert(withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "'"
: "CREATE ZONE test STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.name(), equalTo("TEST"));
assertThat(desc.consistencyMode(), equalTo(ConsistencyMode.STRONG_CONSISTENCY));
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithConsistencyModeStrongConsistency(boolean withPresent) throws SqlParseException {
String sql = withPresent
? "CREATE ZONE test WITH storage_profiles='" + DEFAULT_STORAGE_PROFILE + "',"
+ " CONSISTENCY_MODE='" + ConsistencyMode.STRONG_CONSISTENCY.name() + "'"
: "CREATE ZONE test (CONSISTENCY MODE '" + ConsistencyMode.STRONG_CONSISTENCY.name() + "') "
+ "STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "'] ";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.consistencyMode(), equalTo(ConsistencyMode.STRONG_CONSISTENCY));
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithConsistencyModeHighAvailability(boolean withPresent) throws SqlParseException {
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "',"
+ " CONSISTENCY_MODE='" + ConsistencyMode.HIGH_AVAILABILITY + "'"
: "CREATE ZONE test (CONSISTENCY MODE '" + ConsistencyMode.HIGH_AVAILABILITY + "') "
+ "STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "'] ";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.consistencyMode(), equalTo(ConsistencyMode.HIGH_AVAILABILITY));
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithConsistencyModeInvalid(boolean withPresent) {
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "',"
+ " CONSISTENCY_MODE='MY_CUSTOM_MODE'"
: "CREATE ZONE test (CONSISTENCY MODE 'MY_CUSTOM_MODE') "
+ "STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "'] ";
assertThrows(
SqlException.class,
() -> convert(sql),
"Failed to parse consistency mode: MY_CUSTOM_MODE. Valid values are: [STRONG_CONSISTENCY, HIGH_AVAILABILITY]"
);
}
@Test
public void testMixedOptions() {
String passed = "CREATE ZONE test with partitions=2, replicas=3, storage_profiles='p' S";
assertThrowsWithPos("CREATE ZONE test with partitions=2, replicas=3, storage_profiles='p' STORAGE PROFILES ['profile']",
"STORAGE", passed.length());
passed = "CREATE ZONE test with (";
assertThrowsWithPos("CREATE ZONE test with (partitions 2, replicas 3, storage_profiles='p') STORAGE PROFILES ['profile']",
"(", passed.length());
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithOptions(boolean withPresent) throws SqlParseException {
// Check non-conflicting options.
{
String sql = withPresent
? "CREATE ZONE test with "
+ "partitions=2, "
+ "replicas=5, "
+ "quorum_size=2, " // non-default value
+ "distribution_algorithm='rendezvous', "
+ "data_nodes_filter='$[?(@.region == \"US\")]', "
+ "storage_profiles='" + ROCKSDB_STORAGE_PROFILE + " , " + AIPERSIST_STORAGE_PROFILE + " ' "
: "CREATE ZONE test "
+ "(partitions 2, "
+ "replicas 5, "
+ "quorum size 2, " // non-default value
+ "distribution algorithm 'rendezvous', "
+ "nodes filter '$[?(@.region == \"US\")]') "
+ "storage profiles ['" + ROCKSDB_STORAGE_PROFILE + "' , '" + AIPERSIST_STORAGE_PROFILE + " '] ";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.partitions(), equalTo(2));
assertThat(desc.replicas(), equalTo(5));
assertThat(desc.quorumSize(), equalTo(2));
// TODO https://issues.apache.org/jira/browse/IGNITE-22162
// assertThat(desc.distributionAlgorithm(), equalTo("rendezvous"));
assertThat(desc.filter(), equalTo("$[?(@.region == \"US\")]"));
List<CatalogStorageProfileDescriptor> storageProfiles = desc.storageProfiles().profiles();
assertThat(storageProfiles, hasSize(2));
assertThat(storageProfiles.get(0).storageProfile(), equalTo(ROCKSDB_STORAGE_PROFILE));
assertThat(storageProfiles.get(1).storageProfile(), equalTo(AIPERSIST_STORAGE_PROFILE));
}
// Check remaining options.
{
String sql = withPresent
? "CREATE ZONE test with "
+ "data_nodes_auto_adjust_scale_up=100, "
+ "data_nodes_auto_adjust_scale_down=200, "
+ "storage_profiles='" + ROCKSDB_STORAGE_PROFILE + "'"
: "CREATE ZONE test "
+ "(auto scale up 100, "
+ "auto scale down 200) "
+ "storage profiles ['" + ROCKSDB_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(100));
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(200));
}
// Check option validation.
if (withPresent) {
expectOptionValidationError("CREATE ZONE test with partitions=-1, storage_profiles='p'", "PARTITION");
expectOptionValidationError("CREATE ZONE test with replicas=-1, storage_profiles='p'", "REPLICAS");
assertThrowsWithPos("CREATE ZONE test with replicas=FALL, storage_profiles='p'", "FALL", 32);
emptyProfilesValidationError("CREATE ZONE test with storage_profiles='' ");
emptyProfilesValidationError("CREATE ZONE test with storage_profiles=' ' ");
} else {
assertThrowsWithPos("CREATE ZONE test (partitions -1)", "-", 30);
assertThrowsWithPos("CREATE ZONE test (AUTO SCALE FALL)", "FALL", 30);
assertThrowsWithPos("CREATE ZONE test (AUTO SCALE UP FALL)", "FALL", 33);
assertThrowsWithPos("CREATE ZONE test (AUTO SCALE DOWN FALL)", "FALL", 35);
assertThrowsWithPos("CREATE ZONE test (replicas -1)", "-", 28);
assertThrowsWithPos("CREATE ZONE test (replicas FALL)", "FALL", 28);
assertThrowsWithPos("CREATE ZONE test (replicas 1, partitions -1)", "-", 42);
assertThrowsWithPos("CREATE ZONE test storage_profiles ['']", "storage_profiles", 18);
assertThrowsParseException("CREATE ZONE test (distribution algorithm '')", "Validation Error: Empty character literal "
+ "is not allowed in this context.");
assertThrowsParseException("CREATE ZONE test storage profiles ['']", "Validation Error: Empty character literal "
+ "is not allowed in this context.");
assertThrowsParseException("CREATE ZONE test storage profiles [' ']", "Validation Error: Empty character literal "
+ "is not allowed in this context.");
}
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithReplicasAll(boolean withPresent) throws SqlParseException {
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "', REPLICAS=ALL"
: "CREATE ZONE test (REPLICAS ALL) STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.replicas(), equalTo(DistributionAlgorithm.ALL_REPLICAS));
}
@Test
public void testCreateZoneWithScaleOff() throws SqlParseException {
String sql = "CREATE ZONE test (AUTO SCALE UP OFF) STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(INFINITE_TIMER_VALUE));
sql = "CREATE ZONE test (AUTO SCALE DOWN OFF) STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
cmd = convert(sql);
desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(INFINITE_TIMER_VALUE));
}
@Test
public void testCreateZoneWithAllScaleOff() throws SqlParseException {
String sql = "CREATE ZONE test (AUTO SCALE OFF) STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(INFINITE_TIMER_VALUE));
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(INFINITE_TIMER_VALUE));
}
@Test
public void testAlterZoneWithScaleOff() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE test SET (AUTO SCALE UP OFF)");
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(INFINITE_TIMER_VALUE));
cmd = convert("ALTER ZONE test SET (AUTO SCALE DOWN OFF)");
assertThat(cmd, instanceOf(AlterZoneCommand.class));
desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(INFINITE_TIMER_VALUE));
}
@Test
public void testAlterZoneWithAllScaleOff() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE test SET (AUTO SCALE OFF)");
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(INFINITE_TIMER_VALUE));
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(INFINITE_TIMER_VALUE));
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testSingleNonExistedStorageProfile(boolean withPresent) {
String nonExistedStorageProfileName = "not_existed_profile";
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + nonExistedStorageProfileName + "'"
: "CREATE ZONE test STORAGE PROFILES ['" + nonExistedStorageProfileName + "']";
expectStatementValidationError(
sql,
"Some storage profiles don't exist [missedProfileNames=[" + nonExistedStorageProfileName + "]]."
);
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testSeveralNonExistedStorageProfiles(boolean withPresent) {
String nonExistedStorageProfileName1 = "not_existed_profile_1";
String nonExistedStorageProfileName2 = "not_existed_profile_2";
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + nonExistedStorageProfileName1 + ", " + nonExistedStorageProfileName2 + "'"
: "CREATE ZONE test STORAGE PROFILES ['" + nonExistedStorageProfileName1 + "', '" + nonExistedStorageProfileName2 + "']";
expectStatementValidationError(
sql,
"Some storage profiles don't exist [missedProfileNames=["
+ nonExistedStorageProfileName1 + ", "
+ nonExistedStorageProfileName2 + "]]."
);
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testNonExistedStorageProfilesAmongExistedOnes(boolean withPresent) {
String nonExistedStorageProfileName = "not_existed_profile";
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='"
+ AIPERSIST_STORAGE_PROFILE + ", "
+ nonExistedStorageProfileName + ", "
+ ROCKSDB_STORAGE_PROFILE + "'"
: "CREATE ZONE test STORAGE PROFILES ['"
+ AIPERSIST_STORAGE_PROFILE + "', '"
+ nonExistedStorageProfileName + "', '"
+ ROCKSDB_STORAGE_PROFILE + "']";
expectStatementValidationError(
sql,
"Some storage profiles don't exist [missedProfileNames=[" + nonExistedStorageProfileName + "]]."
);
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testExistedStorageProfileOnDisjointProfileSetsInLogicalTopologySnapshot(boolean withPresent) throws SqlParseException {
when(logicalTopologyService.localLogicalTopology()).thenReturn(new LogicalTopologySnapshot(
0,
List.of(
createLocalNode(0, List.of(AIPERSIST_STORAGE_PROFILE)),
createLocalNode(1, List.of(ROCKSDB_STORAGE_PROFILE)),
createLocalNode(2, List.of(DEFAULT_STORAGE_PROFILE))
)
));
String sql = withPresent
? "CREATE ZONE test WITH STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "'"
: "CREATE ZONE test STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
List<CatalogStorageProfileDescriptor> storageProfiles = invokeAndGetFirstEntry(cmd, NewZoneEntry.class)
.descriptor()
.storageProfiles()
.profiles();
assertThat(storageProfiles, hasSize(1));
assertThat(storageProfiles.get(0).storageProfile(), equalTo(DEFAULT_STORAGE_PROFILE));
}
private static List<Arguments> defaultQuorum() {
return List.of(
Arguments.of(1, 1),
Arguments.of(2, 2),
Arguments.of(5, 3),
Arguments.of(10, 3)
);
}
@ParameterizedTest(name = "replicas = {0}, expectedQuorum = {1}")
@MethodSource("defaultQuorum")
public void testCreateZoneWithQuorumDefault(int replicas, int expectedQuorum) throws SqlParseException {
String sql = "CREATE ZONE test WITH REPLICAS=" + replicas + ", STORAGE_PROFILES='" + DEFAULT_STORAGE_PROFILE + "'";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.quorumSize(), equalTo(expectedQuorum));
}
private static List<Arguments> correctQuorumSize() {
return List.of(
Arguments.of(1, 1),
Arguments.of(2, 2),
Arguments.of(5, 2),
Arguments.of(10, 5)
);
}
@ParameterizedTest(name = "(replicas = {0}, quorum size = {1})")
@MethodSource("correctQuorumSize")
public void testCreateZoneWithQuorum(int replicas, int quorum) throws SqlParseException {
String sql = "CREATE ZONE test (REPLICAS " + replicas + ", QUORUM SIZE " + quorum
+ ") STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
CatalogCommand cmd = convert(sql);
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, NewZoneEntry.class).descriptor();
assertThat(desc.quorumSize(), equalTo(quorum));
}
private static List<Arguments> invalidQuorumSize() {
return List.of(
Arguments.of(1, 2),
Arguments.of(2, 3),
Arguments.of(5, 4),
Arguments.of(10, 1)
);
}
@ParameterizedTest(name = "(replicas {0}, quorum size {1})")
@MethodSource("invalidQuorumSize")
public void testCreateZoneWithInvalidQuorum(int replicas, int quorum) {
String sql = "CREATE ZONE test (REPLICAS " + replicas + ", QUORUM SIZE " + quorum
+ ") STORAGE PROFILES ['" + DEFAULT_STORAGE_PROFILE + "']";
// We can't properly validate quorum size in the parser, so the exception is thrown from the catalog command validation instead.
assertThrows(
CatalogValidationException.class,
() -> convert(sql),
"Specified quorum size doesn't fit into the specified replicas count"
);
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithoutStorageProfileOptionShouldThrowError(boolean withPresent) {
assertThrowsWithPos("CREATE ZONE test", "<EOF>", 16);
if (withPresent) {
emptyProfilesValidationError("CREATE ZONE test with replicas=1");
} else {
assertThrowsWithPos("CREATE ZONE test (replicas 1)", "<EOF>", 29);
}
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void testCreateZoneWithDuplicateOptions(boolean withPresent) {
String sql = withPresent
? "CREATE ZONE test with partitions=2, replicas=0, PARTITIONS=1, STORAGE_PROFILES='profile'"
: "CREATE ZONE test (partitions 2, replicas 0, PARTITIONS 1) STORAGE PROFILES ['profile']";
expectDuplicateOptionError(sql, "PARTITIONS");
}
@Test
public void testRenameZoneCommand() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE test RENAME TO test2");
assertThat(cmd, instanceOf(RenameZoneCommand.class));
when(catalog.zone("TEST")).thenReturn(mock(CatalogZoneDescriptor.class));
AlterZoneEntry entry = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class);
assertThat(entry.descriptor().name(), equalTo("TEST2"));
assertThat(((RenameZoneCommand) cmd).ifExists(), is(false));
}
@Test
public void testRenameZoneIfExistCommand() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE IF EXISTS test RENAME TO test2");
assertThat(cmd, instanceOf(RenameZoneCommand.class));
RenameZoneCommand zoneCmd = (RenameZoneCommand) cmd;
when(catalog.zone("TEST")).thenReturn(mock(CatalogZoneDescriptor.class));
AlterZoneEntry entry = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class);
assertThat(entry.descriptor().name(), equalTo("TEST2"));
assertThat(zoneCmd.ifExists(), is(true));
}
@ParameterizedTest(name = "obsolete = {0}")
@ValueSource(booleans = {true, false})
public void testAlterZoneCommand(boolean obsolete) throws SqlParseException {
CatalogCommand cmd = convert(obsolete
? "ALTER ZONE test SET replicas=5, quorum_size=3"
: "ALTER ZONE test SET (replicas 5, quorum size 3)"
);
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.name(), equalTo("TEST"));
assertThat(desc.replicas(), is(5));
assertThat(desc.quorumSize(), is(3));
assertThat(((AlterZoneCommand) cmd).ifExists(), is(false));
}
@ParameterizedTest(name = "obsolete = {0}")
@ValueSource(booleans = {true, false})
public void testAlterZoneIfExistsCommand(boolean obsolete) throws SqlParseException {
CatalogCommand cmd = convert(obsolete ? "ALTER ZONE IF EXISTS test SET replicas=3" : "ALTER ZONE IF EXISTS test SET (replicas 3)");
assertThat(cmd, instanceOf(AlterZoneCommand.class));
assertThat(((AlterZoneCommand) cmd).ifExists(), is(true));
}
@ParameterizedTest(name = "obsolete = {0}")
@ValueSource(booleans = {true, false})
public void testAlterZoneSetCommand(boolean obsolete) throws SqlParseException {
// Check non-conflicting options.
{
String sql = obsolete
? "ALTER ZONE test SET "
+ "replicas=5, "
+ "quorum_size=3, "
+ "data_nodes_filter='$[?(@.region == \"US\")]'"
: "ALTER ZONE test SET "
+ "(replicas 5, "
+ "quorum size 3, "
+ "nodes filter '$[?(@.region == \"US\")]')";
CatalogCommand cmd = convert(sql);
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.name(), equalTo("TEST"));
assertThat(desc.replicas(), equalTo(5));
assertThat(desc.quorumSize(), equalTo(3));
assertThat(desc.filter(), equalTo("$[?(@.region == \"US\")]"));
}
// Check remaining options.
{
String sql = obsolete
? "ALTER ZONE test SET "
+ "data_nodes_auto_adjust_scale_up=100, "
+ "data_nodes_auto_adjust_scale_down=200"
: "ALTER ZONE test SET "
+ "(auto scale up 100, "
+ "auto scale down 200)";
CatalogCommand cmd = convert(sql);
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.name(), equalTo("TEST"));
assertThat(desc.dataNodesAutoAdjustScaleUp(), equalTo(100));
assertThat(desc.dataNodesAutoAdjustScaleDown(), equalTo(200));
}
}
@ParameterizedTest(name = "obsolete = {0}")
@ValueSource(booleans = {true, false})
public void testAlterZoneReplicasAll(boolean obsolete) throws SqlParseException {
CatalogCommand cmd = convert(obsolete ? "ALTER ZONE test SET replicas=ALL" : "ALTER ZONE test SET (replicas ALL)");
assertThat(cmd, instanceOf(AlterZoneCommand.class));
mockCatalogZone("TEST");
CatalogZoneDescriptor desc = invokeAndGetFirstEntry(cmd, AlterZoneEntry.class).descriptor();
assertThat(desc.replicas(), is(DistributionAlgorithm.ALL_REPLICAS));
}
@Test
public void testAlterZoneSetDefault() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE test SET DEFAULT");
assertThat(cmd, instanceOf(AlterZoneSetDefaultCommand.class));
CatalogZoneDescriptor zoneMock = mock(CatalogZoneDescriptor.class);
when(catalog.zone("TEST")).thenReturn(zoneMock);
SetDefaultZoneEntry entry = invokeAndGetFirstEntry(cmd, SetDefaultZoneEntry.class);
AlterZoneSetDefaultCommand zoneCmd = (AlterZoneSetDefaultCommand) cmd;
assertThat(entry.zoneId(), is(zoneMock.id()));
assertThat(zoneCmd.ifExists(), is(false));
}
@Test
public void testAlterZoneSetDefaultIfExists() throws SqlParseException {
CatalogCommand cmd = convert("ALTER ZONE IF EXISTS test SET DEFAULT");
assertThat(cmd, instanceOf(AlterZoneSetDefaultCommand.class));
assertThat(((AlterZoneSetDefaultCommand) cmd).ifExists(), is(true));
}
@ParameterizedTest(name = "obsolete = {0}, option = {1}")
@MethodSource("numericOptions")
public void testAlterZoneCommandWithInvalidOptions(boolean obsolete, ZoneOptionEnum option) {
String sql = obsolete
? "ALTER ZONE test SET {}=-100"
: "ALTER ZONE test SET ({} -100)";
if (obsolete) {
expectOptionValidationError(format(sql, option.name()), option.name());
} else {
String sqlName = option.sqlName;
String prefix = "ALTER ZONE test SET (";
assertThrowsWithPos(format(sql, sqlName, "-100"), "-", prefix.length() + sqlName.length() + 1 /* start pos*/
+ 1 /* first symbol after bracket*/);
}
}
@Test
public void testDropZone() throws SqlParseException {
CatalogCommand cmd = convert("DROP ZONE test");
assertThat(cmd, instanceOf(DropZoneCommand.class));
CatalogZoneDescriptor zoneMock = mock(CatalogZoneDescriptor.class);
when(catalog.zone("TEST")).thenReturn(zoneMock);
DropZoneEntry entry = invokeAndGetFirstEntry(cmd, DropZoneEntry.class);
assertThat(entry.zoneId(), is(zoneMock.id()));
}
@ParameterizedTest(name = "with syntax = {0}, option = {1}")
@MethodSource("numericOptions")
public void createZoneWithInvalidNumericOptionValue(boolean withPresent, ZoneOptionEnum option) {
String sql = withPresent ? "create zone test_zone with {}={}, storage_profiles='p'" : "create zone test_zone ({} {})";
if (withPresent) {
expectInvalidOptionType(format(sql, option, "'bar'"), option.name());
} else {
String sqlName = option.sqlName;
String prefix = "create zone test_zone (";
int errorPos = prefix.length() + sqlName.length() + 1 /* start pos*/ + 1 /* first symbol after bracket*/;
assertThrowsWithPos(format(sql, sqlName, "'bar'"), "\\'bar\\'", errorPos);
assertThrowsWithPos(format(sql, sqlName, "-1"), "-", errorPos);
}
}
@ParameterizedTest(name = "with syntax = {0}")
@ValueSource(booleans = {true, false})
public void createZoneWithUnexpectedOption(boolean withPresent) {
String sql = withPresent ? "create zone test_zone with ABC=1, storage_profiles='p'" : "create zone test_zone (ABC 1)";
if (withPresent) {
expectUnexpectedOption(sql, "ABC");
} else {
assertThrowsWithPos(sql, "ABC", 24);
}
}
@ParameterizedTest(name = "with syntax = {0}, option = {1}")
@MethodSource("stringOptions")
public void createZoneWithInvalidStringOptionValue(boolean withPresent, ZoneOptionEnum option) {
if (withPresent) {
String sql = format("create zone test_zone with {}={}, storage_profiles='p'", option.name(), "1");
expectInvalidOptionType(sql, option.name());
} else {
String sql = "create zone test_zone ({} {})";
String sqlName = option.sqlName;
String prefix = "create zone test_zone (";
assertThrowsWithPos(format(sql, sqlName, "1"), "1", prefix.length() + sqlName.length() + 1 /* start pos*/
+ 1 /* first symbol after bracket*/);
}
}
@Test
public void createZoneWithInvalidStorageProfiles() {
String profiles = "STORAGE PROFILES [";
String sql = "create zone test_zone {} {}]";
String prefix = "create zone test_zone ";
assertThrowsWithPos(format(sql, profiles, "1"), "1", prefix.length() + profiles.length() + 1 /* start pos*/
+ 1 /* first symbol after bracket*/);
}
@ParameterizedTest
@MethodSource("pureNumericOptions")
public void alterZoneWithInvalidNumericOptionValue(ZoneOptionEnum optionParam) {
String sql = format("alter zone test_zone set {}={}", optionParam.name(), "'bar'");
expectInvalidOptionType(sql, optionParam.name());
}
@Test
public void alterZoneWithUnexpectedOption() {
expectUnexpectedOption("alter zone test_zone set ABC=1", "ABC");
}
private void assertThrowsWithPos(String query, String encountered, int pos) {
assertThrowsParseException(query, format("Encountered \"{}\" at line 1, column {}.", encountered, pos));
}
private void assertThrowsParseException(String query, String message) {
assertThrows(SqlParseException.class, () -> convert(query), message);
}
private static Stream<ZoneOptionEnum> pureNumericOptions() {
return NUMERIC_OPTIONS.stream();
}
private static Stream<Arguments> numericOptions() {
return Stream.of(true, false).flatMap(t1 -> NUMERIC_OPTIONS.stream()
.map(t2 -> Arguments.of(t1, t2))
);
}
private static Stream<Arguments> stringOptions() {
return Stream.of(true, false).flatMap(t1 -> STRING_OPTIONS.stream()
.map(t2 -> Arguments.of(t1, t2))
);
}
private void expectOptionValidationError(String sql, String invalidOption) {
expectStatementValidationError(sql, "Zone option validation failed [option=" + invalidOption);
}
private void emptyProfilesValidationError(String sql) {
expectStatementValidationError(sql, "STORAGE PROFILES can not be empty");
}
private void expectInvalidOptionType(String sql, String invalidOption) {
expectStatementValidationError(sql, "Invalid zone option type [option=" + invalidOption);
}
private void expectUnexpectedOption(String sql, String invalidOption) {
expectStatementValidationError(sql, "Unexpected zone option [option=" + invalidOption);
}
private void expectDuplicateOptionError(String sql, String option) {
expectStatementValidationError(sql, "Duplicate zone option has been specified [option=" + option);
}
private void expectStatementValidationError(String sql, String errorMessageFragment) {
assertThrowsWithCode(
SqlException.class,
STMT_VALIDATION_ERR,
() -> convert(sql),
errorMessageFragment
);
}
private static LogicalNode createLocalNode(int nodeIdx, List<String> storageProfiles) {
return new LogicalNode(
new ClusterNodeImpl(
UUID.randomUUID(),
"node" + nodeIdx,
new NetworkAddress("127.0.0.1", 3344 + nodeIdx)
),
Map.of(),
Map.of(),
storageProfiles
);
}
private void mockCatalogZone(String zoneName) {
CatalogZoneDescriptor zoneMock = mock(CatalogZoneDescriptor.class);
when(zoneMock.name()).thenReturn(zoneName);
when(zoneMock.filter()).thenReturn("");
when(catalog.zone("TEST")).thenReturn(zoneMock);
}
}
|
apache/drill | 38,033 | exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/impl/TDigestFunctions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.expr.fn.impl;
import io.netty.buffer.DrillBuf;
import org.apache.drill.exec.expr.DrillAggFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.BigIntHolder;
import org.apache.drill.exec.expr.holders.NullableBigIntHolder;
import org.apache.drill.exec.expr.holders.BitHolder;
import org.apache.drill.exec.expr.holders.NullableBitHolder;
import org.apache.drill.exec.expr.holders.NullableIntHolder;
import org.apache.drill.exec.expr.holders.NullableFloat8Holder;
import org.apache.drill.exec.expr.holders.NullableFloat4Holder;
import org.apache.drill.exec.expr.holders.Float8Holder;
import org.apache.drill.exec.expr.holders.Float4Holder;
import org.apache.drill.exec.expr.holders.DateHolder;
import org.apache.drill.exec.expr.holders.TimeHolder;
import org.apache.drill.exec.expr.holders.TimeStampHolder;
import org.apache.drill.exec.expr.holders.NullableDateHolder;
import org.apache.drill.exec.expr.holders.NullableTimeHolder;
import org.apache.drill.exec.expr.holders.NullableTimeStampHolder;
import org.apache.drill.exec.expr.holders.ObjectHolder;
import org.apache.drill.exec.expr.holders.IntHolder;
import org.apache.drill.exec.expr.holders.NullableVarBinaryHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
import org.apache.drill.exec.expr.holders.NullableVarCharHolder;
import org.apache.drill.exec.server.options.OptionManager;
import javax.inject.Inject;
@SuppressWarnings("unused")
public class TDigestFunctions {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TDigestFunctions.class);
private TDigestFunctions(){}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class BigIntTDigestFunction implements DrillAggFunc {
@Param BigIntHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableBigIntTDigestFunction implements DrillAggFunc {
@Param NullableBigIntHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class IntTDigestFunction implements DrillAggFunc {
@Param IntHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableIntTDigestFunction implements DrillAggFunc {
@Param NullableIntHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class Float8TDigestFunction implements DrillAggFunc {
@Param Float8Holder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableFloat8TDigestFunction implements DrillAggFunc {
@Param NullableFloat8Holder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class Float4TDigestFunction implements DrillAggFunc {
@Param Float4Holder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableFloat4TDigestFunction implements DrillAggFunc {
@Param NullableFloat4Holder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class BitTDigestFunction implements DrillAggFunc {
@Param BitHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableBitTDigestFunction implements DrillAggFunc {
@Param NullableBitHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class DateTDigestFunction implements DrillAggFunc {
@Param DateHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableDateTDigestFunction implements DrillAggFunc {
@Param NullableDateHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class TimeTDigestFunction implements DrillAggFunc {
@Param TimeHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableTimeTDigestFunction implements DrillAggFunc {
@Param NullableTimeHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class TimeStampTDigestFunction implements DrillAggFunc {
@Param TimeStampHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
tdigest.add(in.value);
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableTimeStampTDigestFunction implements DrillAggFunc {
@Param NullableTimeStampHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
if (in.isSet == 1) {
tdigest.add(in.value);
} else {
// do nothing since we track nulls outside the scope of the histogram
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (tdigest.size() > 0) {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} else {
out.isSet = 0;
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class VarCharTDigestFunction implements DrillAggFunc {
@Param VarCharHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
}
@Override
public void add() {
}
@Override
public void output() {
}
@Override
public void reset() {
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableVarCharTDigestFunction implements DrillAggFunc {
@Param NullableVarCharHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
}
@Override
public void add() {
}
@Override
public void output() {
}
@Override
public void reset() {
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class VarBinaryTDigestFunction implements DrillAggFunc {
@Param VarBinaryHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
}
@Override
public void add() {
}
@Override
public void output() {
}
@Override
public void reset() {
}
}
@FunctionTemplate(name = "tdigest", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class NullableVarBinaryTDigestFunction implements DrillAggFunc {
@Param NullableVarBinaryHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
}
@Override
public void add() {
}
@Override
public void output() {
}
@Override
public void reset() {
}
}
@FunctionTemplate(name = "tdigest_merge", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE)
public static class TDigestMergeFunction implements DrillAggFunc {
@Param NullableVarBinaryHolder in;
@Workspace ObjectHolder work;
@Output NullableVarBinaryHolder out;
@Inject DrillBuf buffer;
@Inject OptionManager options;
@Workspace IntHolder compression;
@Override
public void setup() {
work = new ObjectHolder();
compression.value = (int) options.getLong(org.apache.drill.exec.ExecConstants.TDIGEST_COMPRESSION);
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
@Override
public void add() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
if (in.isSet != 0) {
byte[] buf = org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.toStringFromUTF8(in.start, in.end, in.buffer).getBytes(java.nio.charset.StandardCharsets.UTF_8);
com.tdunning.math.stats.MergingDigest other =
com.tdunning.math.stats.MergingDigest.fromBytes(java.nio.ByteBuffer.wrap(buf));
tdigest.add(other);
}
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to merge TDigest output", e);
}
}
}
@Override
public void output() {
if (work.obj != null) {
com.tdunning.math.stats.MergingDigest tdigest = (com.tdunning.math.stats.MergingDigest) work.obj;
try {
int size = tdigest.smallByteSize();
java.nio.ByteBuffer byteBuf = java.nio.ByteBuffer.allocate(size);
tdigest.asSmallBytes(byteBuf);
out.buffer = buffer = buffer.reallocIfNeeded(size);
out.start = 0;
out.end = size;
out.buffer.setBytes(0, byteBuf.array());
out.isSet = 1;
} catch (Exception e) {
throw new org.apache.drill.common.exceptions.DrillRuntimeException("Failed to get TDigest output", e);
}
} else {
out.isSet = 0;
}
}
@Override
public void reset() {
work.obj = new com.tdunning.math.stats.MergingDigest(compression.value);
}
}
}
|
apache/kafka | 38,132 | tools/src/test/java/org/apache/kafka/tools/streams/ResetStreamsGroupOffsetTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.tools.streams;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.GroupListing;
import org.apache.kafka.clients.admin.ListGroupsOptions;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.streams.GroupProtocol;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValueTimestamp;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.test.TestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import joptsimple.OptionException;
import static java.time.LocalDateTime.now;
import static java.util.stream.Collectors.toMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Timeout(600)
@Tag("integration")
public class ResetStreamsGroupOffsetTest {
private static final String TOPIC_PREFIX = "foo-";
private static final String APP_ID_PREFIX = "streams-group-command-test";
private static final Properties STREAMS_CONFIG = new Properties();
private static final int RECORD_TOTAL = 10;
public static EmbeddedKafkaCluster cluster;
private static String bootstrapServers;
private static Admin adminClient;
@BeforeAll
public static void startCluster() {
final Properties props = new Properties();
cluster = new EmbeddedKafkaCluster(2, props);
cluster.start();
bootstrapServers = cluster.bootstrapServers();
adminClient = cluster.createAdminClient();
createStreamsConfig(bootstrapServers);
}
private static void createStreamsConfig(String bootstrapServers) {
STREAMS_CONFIG.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
STREAMS_CONFIG.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
STREAMS_CONFIG.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
STREAMS_CONFIG.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
STREAMS_CONFIG.put(StreamsConfig.GROUP_PROTOCOL_CONFIG, GroupProtocol.STREAMS.name().toLowerCase(Locale.getDefault()));
STREAMS_CONFIG.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2);
}
@AfterEach
public void deleteTopicsAndGroups() {
try (final Admin adminClient = cluster.createAdminClient()) {
// delete all topics
final Set<String> topics = adminClient.listTopics().names().get();
adminClient.deleteTopics(topics).all().get();
// delete all groups
List<String> groupIds =
adminClient.listGroups(ListGroupsOptions.forStreamsGroups().timeoutMs(1000)).all().get()
.stream().map(GroupListing::groupId).toList();
adminClient.deleteStreamsGroups(groupIds).all().get();
} catch (final UnknownTopicOrPartitionException ignored) {
} catch (final ExecutionException | InterruptedException e) {
if (!(e.getCause() instanceof UnknownTopicOrPartitionException)) {
throw new RuntimeException(e);
}
}
}
@AfterAll
public static void closeCluster() {
cluster.stop();
}
@Test
public void testResetWithUnrecognizedOption() {
String[] args = new String[]{"--unrecognized-option", "--bootstrap-server", bootstrapServers, "--reset-offsets", "--all-groups", "--all-input-topics", "--to-offset", "5"};
assertThrows(OptionException.class, () -> getStreamsGroupService(args));
}
@Test
public void testResetOffsetsWithoutGroupOption() {
final String[] args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--to-offset", "5"};
AtomicBoolean exited = new AtomicBoolean(false);
Exit.setExitProcedure(((statusCode, message) -> {
assertNotEquals(0, statusCode);
assertTrue(message.contains("Option [reset-offsets] takes one of these options: [all-groups], [group]"));
exited.set(true);
}));
try {
getStreamsGroupService(args);
} finally {
assertTrue(exited.get());
}
}
@Test
public void testResetOffsetsWithDeleteInternalTopicsOption() {
final String[] args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--all-groups", "--all-input-topics", "--to-offset", "5", "--delete-all-internal-topics"};
AtomicBoolean exited = new AtomicBoolean(false);
Exit.setExitProcedure(((statusCode, message) -> {
assertNotEquals(0, statusCode);
assertTrue(message.contains("Option [delete-all-internal-topics] takes [execute] when [reset-offsets] is used"));
exited.set(true);
}));
try {
getStreamsGroupService(args);
} finally {
assertTrue(exited.get());
}
}
@Test
public void testResetOffset() throws Exception {
final String appId = generateRandomAppId();
final String topic1 = generateRandomTopic();
final String topic2 = generateRandomTopic();
final int numOfPartitions = 2;
String[] args;
produceConsumeShutdown(appId, topic1, topic2, RECORD_TOTAL * numOfPartitions * 2);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic1);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic2);
/////////////////////////////////////////////// Specific topic (--topic topic1) ////////////////////////////////////////////////
// reset to specific offset, offset already on 10
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-offset", "5"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 5L, 10L, 0, 1);
resetForNextTest(appId, 10L, topic1);
// reset to specific offset when after end offset, offset already on 10
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-offset", "30"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 20L, 10L, 0, 1);
// reset to specific offset when before begin offset, offset already on 20
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-offset", "-30"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 0L, 20L, 0, 1);
resetForNextTest(appId, 10L, topic1);
// reset to specific date time
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime dateTime = now().minusDays(1);
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-datetime", format.format(dateTime)};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 0L, 10L, 0, 1);
resetForNextTest(appId, 10L, topic1);
// reset by duration to earliest
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--by-duration", "PT5M"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 0L, 10L, 0, 1);
resetForNextTest(appId, 10L, topic1);
// reset to earliest
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-earliest"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 0L, 10L, 0, 1);
resetForNextTest(appId, 10L, topic1);
// reset to latest
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-latest"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 20L, 10L, 0, 1);
resetForNextTest(appId, 5L, topic1);
// reset to current
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-current"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 5L, 5L, 0, 1);
// reset offset shift+. The current offset is 5, as of the prev test is executed (by --execute)
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--shift-by", "3"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 8L, 5L, 0, 1);
// reset offset shift-. The current offset is 8, as of the prev test is executed (by --execute)
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--shift-by", "-3"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 5L, 8L, 0, 1);
// reset offset shift by lower than earliest. The current offset is 5, as of the prev test is executed (by --execute)
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--shift-by", "-150"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 0L, 5L, 0, 1);
// reset offset shift by higher than latest. The current offset is 0, as of the prev test is executed (by --execute)
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--shift-by", "150"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 20L, 0L, 0, 1);
// export to file
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--to-offset", "5", "--export"};
File file = TestUtils.tempFile("reset", ".csv");
Map<TopicPartition, Long> exp = Map.of(new TopicPartition(topic1, 0), 5L, new TopicPartition(topic1, 1), 5L);
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
Map<String, Map<TopicPartition, OffsetAndMetadata>> exportedOffsets = service.resetOffsets();
writeContentToFile(file, service.exportOffsetsToCsv(exportedOffsets));
assertEquals(exp, toOffsetMap(exportedOffsets.get(appId)));
}
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--from-file", file.getCanonicalPath()};
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
Map<String, Map<TopicPartition, OffsetAndMetadata>> importedOffsets = service.resetOffsets();
assertEquals(exp, toOffsetMap(importedOffsets.get(appId)));
}
///////////////////////////////////////// Specific topic and partition (--topic topic1, --topic topic2) /////////////////////////////////////////
resetForNextTest(appId, 10L, topic1);
// reset to specific offset
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1 + ":1", "--to-offset", "5"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, 5L, 10L, 1);
resetForNextTest(appId, 10L, topic1);
// reset both partitions of topic1 and topic2:1 to specific offset
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId,
"--input-topic", topic1, "--input-topic", topic2 + ":1", "--to-offset", "5"};
final Map<TopicPartition, Long> expectedOffsets = Map.of(
new TopicPartition(topic1, 0), 5L,
new TopicPartition(topic1, 1), 5L,
new TopicPartition(topic2, 1), 5L);
resetOffsetsAndAssert(args, appId, List.of(topic1, topic2), expectedOffsets,
Map.of(
new TopicPartition(topic1, 0), 10L,
new TopicPartition(topic1, 1), 10L,
new TopicPartition(topic2, 0), 10L,
new TopicPartition(topic2, 1), 10L));
resetOffsetsAndAssert(addTo(args, "--execute"), appId, List.of(topic1, topic2), expectedOffsets,
Map.of(new TopicPartition(topic1, 0), 5L,
new TopicPartition(topic1, 1), 5L,
new TopicPartition(topic2, 0), 10L,
new TopicPartition(topic2, 1), 5L));
///////////////////////////////////////// All topics (--all-input-topics) /////////////////////////////////////////
resetForNextTest(appId, 10L, topic1, topic2);
// reset to specific offset
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--all-input-topics", "--to-offset", "5"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, topic2, 5L, 10L);
resetForNextTest(appId, 10L, topic1, topic2);
// reset to specific offset with two --topic options
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--input-topic", topic2, "--to-offset", "5"};
resetOffsetsAndAssertForDryRunAndExecute(args, appId, topic1, topic2, 5L, 10L);
resetForNextTest(appId, 10L, topic1, topic2);
// export to file
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--all-input-topics", "--to-offset", "5", "--export"};
file = TestUtils.tempFile("reset-all", ".csv");
exp = Map.of(new TopicPartition(topic1, 0), 5L,
new TopicPartition(topic1, 1), 5L,
new TopicPartition(topic2, 0), 5L,
new TopicPartition(topic2, 1), 5L);
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
Map<String, Map<TopicPartition, OffsetAndMetadata>> exportedOffsets = service.resetOffsets();
writeContentToFile(file, service.exportOffsetsToCsv(exportedOffsets));
assertEquals(exp, toOffsetMap(exportedOffsets.get(appId)));
}
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--input-topic", topic1, "--from-file", file.getCanonicalPath()};
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
Map<String, Map<TopicPartition, OffsetAndMetadata>> importedOffsets = service.resetOffsets();
assertEquals(exp, toOffsetMap(importedOffsets.get(appId)));
}
// assert that the internal topics are not deleted
assertEquals(2, getInternalTopics(appId).size());
}
@Test
public void testResetOffsetsWithDeleteSpecifiedInternalTopics() throws Exception {
final String appId = generateRandomAppId();
final String internalTopic = appId + "-aggregated_value-changelog";
final String topic1 = generateRandomTopic();
final String topic2 = generateRandomTopic();
final int numOfPartitions = 2;
String[] args;
produceConsumeShutdown(appId, topic1, topic2, RECORD_TOTAL * numOfPartitions * 2);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic1);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic2);
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--all-input-topics", "--execute", "--to-offset", "5",
"--delete-internal-topic", internalTopic
};
resetOffsetsAndAssertInternalTopicDeletion(args, appId, internalTopic);
}
@Test
public void testResetOffsetsWithDeleteAllInternalTopics() throws Exception {
final String appId = generateRandomAppId();
final String topic1 = generateRandomTopic();
final String topic2 = generateRandomTopic();
final int numOfPartitions = 2;
String[] args;
produceConsumeShutdown(appId, topic1, topic2, RECORD_TOTAL * numOfPartitions * 2);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic1);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic2);
args = new String[]{"--bootstrap-server", bootstrapServers, "--reset-offsets", "--group", appId, "--all-input-topics", "--delete-all-internal-topics", "--execute", "--to-offset", "5"};
resetOffsetsAndAssertInternalTopicDeletion(args, appId);
}
private void resetForNextTest(String appId, long desiredOffset, String... topics) throws ExecutionException, InterruptedException {
Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
for (String topic : topics) {
offsets.put(new TopicPartition(topic, 0), new OffsetAndMetadata(desiredOffset));
offsets.put(new TopicPartition(topic, 1), new OffsetAndMetadata(desiredOffset));
}
adminClient.alterStreamsGroupOffsets(appId, offsets).all().get();
Map<TopicPartition, Long> committedOffsets = committedOffsets(List.of(topics), appId);
for (TopicPartition tp: offsets.keySet()) {
assertEquals(desiredOffset, committedOffsets.get(tp));
}
}
private void AssertCommittedOffsets(String appId,
String topic,
long expectedCommittedOffset,
int... partitions) throws ExecutionException, InterruptedException {
List<TopicPartition> affectedTPs = Arrays.stream(partitions)
.mapToObj(partition -> new TopicPartition(topic, partition))
.toList();
Map<TopicPartition, Long> committedOffsets = committedOffsets(List.of(topic), appId);
for (TopicPartition tp: affectedTPs) {
assertEquals(expectedCommittedOffset, committedOffsets.get(tp));
}
}
private void AssertCommittedOffsets(String appId,
String topic1,
String topic2,
long expectedCommittedOffset) throws ExecutionException, InterruptedException {
TopicPartition tp10 = new TopicPartition(topic1, 0);
TopicPartition tp11 = new TopicPartition(topic2, 0);
TopicPartition tp20 = new TopicPartition(topic1, 1);
TopicPartition tp21 = new TopicPartition(topic2, 1);
Map<TopicPartition, Long> committedOffsets = committedOffsets(List.of(topic1, topic2), appId);
assertEquals(Map.of(
tp10, expectedCommittedOffset,
tp20, expectedCommittedOffset,
tp11, expectedCommittedOffset,
tp21, expectedCommittedOffset), committedOffsets);
}
/**
* Resets offsets for a specific topic and partition(s) and verifies the results.
*
* <p>This method performs the following steps:</p>
* <ul>
* <li>Resets offsets for the specified topic and partitions using the provided arguments.</li>
* <li>Asserts that the reset offsets match the expected offsets.</li>
* <li>Asserts that the committed offsets match the expected committed offsets.</li>
* </ul>
*
* @param args The command-line arguments for resetting offsets.
* @param appId The application ID for the Kafka Streams application.
* @param topic The topic for which offsets will be reset.
* @param expectedOffset The expected offset value after the reset.
* @param expectedCommittedOffset The expected committed offset value after the reset.
* @param partitions The partitions of the topic to reset offsets for.
* @throws ExecutionException If an error occurs during the execution of the reset operation.
* @throws InterruptedException If the thread is interrupted during the reset operation.
*/
private void resetOffsetsAndAssert(String[] args,
String appId,
String topic,
long expectedOffset,
long expectedCommittedOffset,
int... partitions) throws ExecutionException, InterruptedException {
Map<String, Map<TopicPartition, Long>> resetOffsetsResultByGroup;
Map<TopicPartition, Long> expectedOffetMap = Arrays.stream(partitions)
.boxed()
.collect(Collectors.toMap(
partition -> new TopicPartition(topic, partition),
partition -> expectedOffset
));
Map<String, Map<TopicPartition, Long>> expectedResetResults = Map.of(appId, expectedOffetMap);
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
resetOffsetsResultByGroup = convertOffsetsToLong(service.resetOffsets());
}
// assert that the reset offsets are as expected
assertEquals(expectedResetResults, resetOffsetsResultByGroup);
assertEquals(expectedResetResults.size(), resetOffsetsResultByGroup.size());
// assert that the committed offsets are as expected
AssertCommittedOffsets(appId, topic, expectedCommittedOffset, partitions);
}
private void resetOffsetsAndAssertInternalTopicDeletion(String[] args, String appId, String... specifiedInternalTopics) throws InterruptedException {
List<String> specifiedInternalTopicsList = List.of(specifiedInternalTopics);
Set<String> allInternalTopics = getInternalTopics(appId);
specifiedInternalTopicsList.forEach(allInternalTopics::remove);
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
service.resetOffsets();
}
// assert that the internal topics are deleted
if (specifiedInternalTopics.length > 0) {
TestUtils.waitForCondition(
() -> getInternalTopics(appId).size() == allInternalTopics.size(),
30_000, "Internal topics were not deleted as expected after reset"
);
// verify that the specified internal topics were deleted
Set<String> internalTopicsAfterReset = getInternalTopics(appId);
specifiedInternalTopicsList.forEach(topic ->
assertFalse(internalTopicsAfterReset.contains(topic),
"Internal topic '" + topic + "' was not deleted as expected after reset")
);
} else {
TestUtils.waitForCondition(() -> {
Set<String> internalTopicsAfterReset = getInternalTopics(appId);
return internalTopicsAfterReset.isEmpty();
}, 30_000, "Internal topics were not deleted after reset");
}
}
private Set<String> getInternalTopics(String appId) {
try {
Set<String> topics = adminClient.listTopics().names().get();
return topics.stream()
.filter(topic -> topic.startsWith(appId + "-"))
.filter(topic -> topic.endsWith("-changelog") || topic.endsWith("-repartition"))
.collect(Collectors.toSet());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
/**
* Resets offsets for two topics and verifies the results.
*
* <p>This method performs the following steps:</p>
* <ul>
* <li>Resets offsets for the specified topics using the provided arguments.</li>
* <li>Asserts that the reset offsets match the expected offsets.</li>
* <li>Asserts that the committed offsets match the expected committed offsets.</li>
* </ul>
*
* @param args The command-line arguments for resetting offsets.
* @param appId The application ID for the Kafka Streams application.
* @param topic1 The first topic for which offsets will be reset.
* @param topic2 The second topic for which offsets will be reset.
* @param expectedOffset The expected offset value after the reset.
* @param expectedCommittedOffset The expected committed offset value after the reset.
* @throws ExecutionException If an error occurs during the execution of the reset operation.
* @throws InterruptedException If the thread is interrupted during the reset operation.
*/
private void resetOffsetsAndAssert(String[] args,
String appId,
String topic1,
String topic2,
long expectedOffset,
long expectedCommittedOffset) throws ExecutionException, InterruptedException {
Map<String, Map<TopicPartition, Long>> resetOffsetsResultByGroup;
Map<String, Map<TopicPartition, Long>> expectedResetResults = Map.of(
appId, Map.of(
new TopicPartition(topic1, 0), expectedOffset,
new TopicPartition(topic2, 0), expectedOffset,
new TopicPartition(topic1, 1), expectedOffset,
new TopicPartition(topic2, 1), expectedOffset
)
);
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
resetOffsetsResultByGroup = convertOffsetsToLong(service.resetOffsets());
}
// assert that the reset offsets are as expected
assertEquals(expectedResetResults, resetOffsetsResultByGroup);
assertEquals(expectedResetResults.size(), resetOffsetsResultByGroup.size());
// assert that the committed offsets are as expected
AssertCommittedOffsets(appId, topic1, topic2, expectedCommittedOffset);
}
/**
* Resets offsets for the specified topics and verifies the results.
*
* <p>This method performs the following steps:</p>
* <ul>
* <li>Resets offsets for the given topics using the provided arguments.</li>
* <li>Asserts that the reset offsets match the expected offsets.</li>
* <li>Asserts that the committed offsets match the expected committed offsets.</li>
* </ul>
*
* @param args The command-line arguments for resetting offsets.
* @param appId The application ID for the Kafka Streams application.
* @param topics The list of topics for which offsets will be reset.
* @param expectedOffsets A map of expected offsets for each topic partition after the reset.
* @param expectedCommittedOffsets A map of expected committed offsets for each topic partition after the reset.
* @throws ExecutionException If an error occurs during the execution of the reset operation.
* @throws InterruptedException If the thread is interrupted during the reset operation.
*/
private void resetOffsetsAndAssert(String[] args,
String appId,
List<String> topics,
Map<TopicPartition, Long> expectedOffsets,
Map<TopicPartition, Long> expectedCommittedOffsets) throws ExecutionException, InterruptedException {
Map<TopicPartition, Long> resetOffsetsResult;
try (StreamsGroupCommand.StreamsGroupService service = getStreamsGroupService(args)) {
resetOffsetsResult = convertOffsetsToLong(service.resetOffsets()).get(appId);
}
// assert that the reset offsets are as expected
assertEquals(expectedOffsets, resetOffsetsResult);
assertEquals(expectedOffsets.size(), resetOffsetsResult.size());
// assert that the committed offsets are as expected
assertEquals(expectedCommittedOffsets, committedOffsets(topics, appId));
}
private void resetOffsetsAndAssertForDryRunAndExecute(String[] args,
String appId,
String topic,
long expectedOffset,
long expectedCommittedOffset,
int... partitions) throws ExecutionException, InterruptedException {
resetOffsetsAndAssert(args, appId, topic, expectedOffset, expectedCommittedOffset, partitions);
resetOffsetsAndAssert(addTo(args, "--dry-run"), appId, topic, expectedOffset, expectedCommittedOffset, partitions);
resetOffsetsAndAssert(addTo(args, "--execute"), appId, topic, expectedOffset, expectedOffset, partitions);
}
private void resetOffsetsAndAssertForDryRunAndExecute(String[] args,
String appId,
String topic1,
String topic2,
long expectedOffset,
long expectedCommittedOffset) throws ExecutionException, InterruptedException {
resetOffsetsAndAssert(args, appId, topic1, topic2, expectedOffset, expectedCommittedOffset);
resetOffsetsAndAssert(addTo(args, "--dry-run"), appId, topic1, topic2, expectedOffset, expectedCommittedOffset);
resetOffsetsAndAssert(addTo(args, "--execute"), appId, topic1, topic2, expectedOffset, expectedOffset);
}
private Map<TopicPartition, Long> committedOffsets(List<String> topics,
String group) throws ExecutionException, InterruptedException {
return adminClient.listConsumerGroupOffsets(group)
.all().get()
.get(group).entrySet()
.stream()
.filter(e -> topics.contains(e.getKey().topic()))
.collect(toMap(Map.Entry::getKey, e -> e.getValue().offset()));
}
private static Map<String, Map<TopicPartition, Long>> convertOffsetsToLong(Map<String, Map<TopicPartition, OffsetAndMetadata>> map) {
return map.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> e.getValue().entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e1 -> e1.getValue().offset()))));
}
private Map<TopicPartition, Long> toOffsetMap(Map<TopicPartition, OffsetAndMetadata> map) {
return map.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, e -> e.getValue().offset()));
}
private StreamsGroupCommand.StreamsGroupService getStreamsGroupService(String[] args) {
StreamsGroupCommandOptions opts = StreamsGroupCommandOptions.fromArgs(args);
return new StreamsGroupCommand.StreamsGroupService(
opts,
Map.of(AdminClientConfig.RETRIES_CONFIG, Integer.toString(Integer.MAX_VALUE))
);
}
private void writeContentToFile(File file, String content) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(content);
}
}
private String[] addTo(String[] args, String... extra) {
List<String> res = new ArrayList<>(List.of(args));
res.addAll(List.of(extra));
return res.toArray(new String[0]);
}
private String generateRandomTopic() {
return TOPIC_PREFIX + TestUtils.randomString(10);
}
private String generateRandomAppId() {
return APP_ID_PREFIX + TestUtils.randomString(10);
}
/**
* Produces messages to two partitions of the specified topic and consumes them.
*
* @param appId The application ID for the Kafka Streams application.
* @param topic1 The first topic to produce and consume messages from.
* @param topic2 The second topic to produce and consume messages from.
* @param numOfCommittedMessages The number of committed messages to process before shutting down.
*/
private void produceConsumeShutdown(String appId, String topic1, String topic2, long numOfCommittedMessages) throws Exception {
STREAMS_CONFIG.put(StreamsConfig.APPLICATION_ID_CONFIG, appId);
cluster.createTopic(topic1, 2);
cluster.createTopic(topic2, 2);
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, String> inputStream1 = builder.stream(topic1);
final KStream<String, String> inputStream2 = builder.stream(topic2);
final AtomicInteger recordCount = new AtomicInteger(0);
final KTable<String, String> valueCounts = inputStream1.merge(inputStream2)
// Explicit repartition step with a custom internal topic name
.groupBy((key, value) -> key, Grouped.with(Serdes.String(), Serdes.String()))
.aggregate(
() -> "()",
(key, value, aggregate) -> aggregate + ",(" + key + ": " + value + ")",
Materialized.as("aggregated_value"));
valueCounts.toStream().peek((key, value) -> {
if (recordCount.incrementAndGet() > numOfCommittedMessages) {
throw new IllegalStateException("Crash on the " + numOfCommittedMessages + " record");
}
});
final KafkaStreams streams = new KafkaStreams(builder.build(), STREAMS_CONFIG);
streams.cleanUp();
streams.start();
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic1);
produceMessagesOnTwoPartitions(RECORD_TOTAL, topic2);
TestUtils.waitForCondition(() -> streams.state().equals(KafkaStreams.State.RUNNING),
"Expected RUNNING state but streams is on " + streams.state());
try {
TestUtils.waitForCondition(() -> recordCount.get() == numOfCommittedMessages,
"Expected " + numOfCommittedMessages + " records processed but only got " + recordCount.get());
} catch (final Exception e) {
e.printStackTrace();
} finally {
assertEquals(numOfCommittedMessages, recordCount.get(), "Expected " + numOfCommittedMessages + " records processed but only got " + recordCount.get());
streams.close();
}
}
/**
* Produces messages to two partitions of the specified topic.
*
* @param numOfMessages The number of messages to produce for each partition.
* @param topic The topic to which the messages will be produced.
*/
private static void produceMessagesOnTwoPartitions(final int numOfMessages, final String topic) {
// partition 0
List<KeyValueTimestamp<String, String>> data = new ArrayList<>(numOfMessages);
for (long v = 0; v < numOfMessages; ++v) {
data.add(new KeyValueTimestamp<>(v + "0" + topic, v + "0", cluster.time.milliseconds()));
}
IntegrationTestUtils.produceSynchronously(
TestUtils.producerConfig(bootstrapServers, StringSerializer.class, StringSerializer.class),
false,
topic,
Optional.of(0),
data
);
// partition 1
data = new ArrayList<>(numOfMessages);
for (long v = 0; v < 10; ++v) {
data.add(new KeyValueTimestamp<>(v + "1" + topic, v + "1", cluster.time.milliseconds()));
}
IntegrationTestUtils.produceSynchronously(
TestUtils.producerConfig(bootstrapServers, StringSerializer.class, StringSerializer.class),
false,
topic,
Optional.of(1),
data
);
}
}
|
apache/ozone | 38,312 | hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/storage/ContainerProtocolCalls.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.hdds.scm.storage;
import static java.util.Collections.singletonList;
import static org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Result.BLOCK_TOKEN_VERIFICATION_FAILED;
import io.opentelemetry.api.trace.Span;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import org.apache.hadoop.hdds.annotation.InterfaceStability;
import org.apache.hadoop.hdds.client.BlockID;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.BlockData;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChecksumType;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ChunkInfo;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.CloseContainerRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ContainerCommandResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.DatanodeBlockID;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.EchoRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.EchoResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.FinalizeBlockRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.GetBlockRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.GetBlockResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.GetSmallFileRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.GetSmallFileResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.KeyValue;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ListBlockRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ListBlockResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.PutBlockRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.PutSmallFileRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.PutSmallFileResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadChunkResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadContainerRequestProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.ReadContainerResponseProto;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.Type;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.WriteChunkRequestProto;
import org.apache.hadoop.hdds.scm.XceiverClientReply;
import org.apache.hadoop.hdds.scm.XceiverClientSpi;
import org.apache.hadoop.hdds.scm.XceiverClientSpi.Validator;
import org.apache.hadoop.hdds.scm.container.common.helpers.BlockNotCommittedException;
import org.apache.hadoop.hdds.scm.container.common.helpers.ContainerNotOpenException;
import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
import org.apache.hadoop.hdds.security.token.OzoneBlockTokenIdentifier;
import org.apache.hadoop.hdds.tracing.TracingUtil;
import org.apache.hadoop.ozone.common.Checksum;
import org.apache.hadoop.ozone.common.ChecksumData;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.ratis.thirdparty.com.google.protobuf.ByteString;
import org.apache.ratis.util.function.CheckedFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of all container protocol calls performed by Container
* clients.
*/
public final class ContainerProtocolCalls {
private static final Logger LOG = LoggerFactory.getLogger(ContainerProtocolCalls.class);
private static final List<Validator> VALIDATORS = createValidators();
/**
* There is no need to instantiate this class.
*/
private ContainerProtocolCalls() {
}
/**
* Calls the container protocol to list blocks in container.
*
* @param xceiverClient client to perform call
* @param containerID the ID of the container to list block
* @param startLocalID the localID of the first block to get
* @param count max number of blocks to get
* @param token a token for this block (may be null)
* @return container protocol list block response
* @throws IOException if there is an I/O error while performing the call
*/
public static ListBlockResponseProto listBlock(XceiverClientSpi xceiverClient,
long containerID, Long startLocalID, int count,
Token<? extends TokenIdentifier> token) throws IOException {
ListBlockRequestProto.Builder listBlockBuilder =
ListBlockRequestProto.newBuilder()
.setCount(count);
if (startLocalID != null) {
listBlockBuilder.setStartLocalID(startLocalID);
}
// datanodeID doesn't matter for read only requests
String datanodeID =
xceiverClient.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder()
.setCmdType(Type.ListBlock)
.setContainerID(containerID)
.setDatanodeUuid(datanodeID)
.setListBlock(listBlockBuilder.build());
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
xceiverClient.sendCommand(request, getValidatorList());
return response.getListBlock();
}
static <T> T tryEachDatanode(Pipeline pipeline,
CheckedFunction<DatanodeDetails, T, IOException> op,
Function<DatanodeDetails, String> toErrorMessage)
throws IOException {
final Set<DatanodeDetails> excluded = new HashSet<>();
for (; ;) {
final DatanodeDetails d = pipeline.getClosestNode(excluded);
try {
return op.apply(d);
} catch (IOException e) {
Span span = TracingUtil.getActiveSpan();
if (e instanceof StorageContainerException) {
StorageContainerException sce = (StorageContainerException)e;
// Block token expired. There's no point retrying other DN.
// Throw the exception to request a new block token right away.
if (sce.getResult() == BLOCK_TOKEN_VERIFICATION_FAILED) {
span.addEvent("block token verification failed at DN " + d);
throw e;
}
}
span.addEvent("failed to connect to DN " + d);
excluded.add(d);
if (excluded.size() < pipeline.size()) {
LOG.warn(toErrorMessage.apply(d)
+ "; will try another datanode.", e);
} else {
throw e;
}
}
}
}
/**
* Calls the container protocol to get a container block.
*
* @param xceiverClient client to perform call
* @param validators functions to validate the response
* @param blockID blockID to identify container
* @param token a token for this block (may be null)
* @return container protocol get block response
* @throws IOException if there is an I/O error while performing the call
*/
public static GetBlockResponseProto getBlock(XceiverClientSpi xceiverClient,
List<Validator> validators, BlockID blockID, Token<? extends TokenIdentifier> token,
Map<DatanodeDetails, Integer> replicaIndexes) throws IOException {
ContainerCommandRequestProto.Builder builder = ContainerCommandRequestProto
.newBuilder()
.setCmdType(Type.GetBlock)
.setContainerID(blockID.getContainerID());
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
return tryEachDatanode(xceiverClient.getPipeline(),
d -> getBlock(xceiverClient, validators, builder, blockID, d, replicaIndexes),
d -> toErrorMessage(blockID, d));
}
static String toErrorMessage(BlockID blockId, DatanodeDetails d) {
return String.format("Failed to get block #%s in container #%s from %s",
blockId.getLocalID(), blockId.getContainerID(), d);
}
public static GetBlockResponseProto getBlock(XceiverClientSpi xceiverClient,
BlockID datanodeBlockID,
Token<? extends TokenIdentifier> token, Map<DatanodeDetails, Integer> replicaIndexes) throws IOException {
return getBlock(xceiverClient, getValidatorList(), datanodeBlockID, token, replicaIndexes);
}
private static GetBlockResponseProto getBlock(XceiverClientSpi xceiverClient,
List<Validator> validators,
ContainerCommandRequestProto.Builder builder, BlockID blockID,
DatanodeDetails datanode, Map<DatanodeDetails, Integer> replicaIndexes) throws IOException {
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
final DatanodeBlockID.Builder datanodeBlockID = blockID.getDatanodeBlockIDProtobufBuilder();
int replicaIndex = replicaIndexes.getOrDefault(datanode, 0);
if (replicaIndex > 0) {
datanodeBlockID.setReplicaIndex(replicaIndex);
}
final GetBlockRequestProto.Builder readBlockRequest = GetBlockRequestProto.newBuilder()
.setBlockID(datanodeBlockID.build());
final ContainerCommandRequestProto request = builder
.setDatanodeUuid(datanode.getUuidString())
.setGetBlock(readBlockRequest).build();
ContainerCommandResponseProto response =
xceiverClient.sendCommand(request, validators);
return response.getGetBlock();
}
/**
* Calls the container protocol to get the length of a committed block.
*
* @param xceiverClient client to perform call
* @param blockID blockId for the Block
* @param token a token for this block (may be null)
* @return container protocol getLastCommittedBlockLength response
* @throws IOException if there is an I/O error while performing the call
*/
public static ContainerProtos.GetCommittedBlockLengthResponseProto
getCommittedBlockLength(
XceiverClientSpi xceiverClient, BlockID blockID,
Token<OzoneBlockTokenIdentifier> token)
throws IOException {
ContainerProtos.GetCommittedBlockLengthRequestProto.Builder
getBlockLengthRequestBuilder =
ContainerProtos.GetCommittedBlockLengthRequestProto.newBuilder().
setBlockID(blockID.getDatanodeBlockIDProtobuf());
String id = xceiverClient.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder()
.setCmdType(Type.GetCommittedBlockLength)
.setContainerID(blockID.getContainerID())
.setDatanodeUuid(id)
.setGetCommittedBlockLength(getBlockLengthRequestBuilder);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
xceiverClient.sendCommand(request, getValidatorList());
return response.getGetCommittedBlockLength();
}
/**
* Calls the container protocol to put a container block.
*
* @param xceiverClient client to perform call
* @param containerBlockData block data to identify container
* @param eof whether this is the last putBlock for the same block
* @param tokenString a serialized token for this block (may be null)
* @return putBlockResponse
* @throws IOException if there is an error while performing the call
*/
public static XceiverClientReply putBlockAsync(XceiverClientSpi xceiverClient,
BlockData containerBlockData,
boolean eof,
String tokenString)
throws IOException, InterruptedException, ExecutionException {
final ContainerCommandRequestProto request = getPutBlockRequest(
xceiverClient.getPipeline(), containerBlockData, eof, tokenString);
return xceiverClient.sendCommandAsync(request);
}
/**
* Calls the container protocol to finalize a container block.
*
* @param xceiverClient client to perform call
* @param blockID block ID to identify block
* @param token a token for this block (may be null)
* @return FinalizeBlockResponseProto
* @throws IOException if there is an I/O error while performing the call
*/
public static ContainerProtos.FinalizeBlockResponseProto finalizeBlock(
XceiverClientSpi xceiverClient, DatanodeBlockID blockID,
Token<OzoneBlockTokenIdentifier> token)
throws IOException {
FinalizeBlockRequestProto.Builder finalizeBlockRequest =
FinalizeBlockRequestProto.newBuilder().setBlockID(blockID);
String id = xceiverClient.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder().setCmdType(Type.FinalizeBlock)
.setContainerID(blockID.getContainerID())
.setDatanodeUuid(id)
.setFinalizeBlock(finalizeBlockRequest);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
xceiverClient.sendCommand(request, getValidatorList());
return response.getFinalizeBlock();
}
public static ContainerCommandRequestProto getPutBlockRequest(
Pipeline pipeline, BlockData containerBlockData, boolean eof,
String tokenString) throws IOException {
PutBlockRequestProto.Builder createBlockRequest =
PutBlockRequestProto.newBuilder()
.setBlockData(containerBlockData)
.setEof(eof);
final String id = pipeline.getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder().setCmdType(Type.PutBlock)
.setContainerID(containerBlockData.getBlockID().getContainerID())
.setDatanodeUuid(id)
.setPutBlock(createBlockRequest);
if (tokenString != null) {
builder.setEncodedToken(tokenString);
}
return builder.build();
}
/**
* Calls the container protocol to read a chunk.
*
* @param xceiverClient client to perform call
* @param chunk information about chunk to read
* @param blockID ID of the block
* @param validators functions to validate the response
* @param token a token for this block (may be null)
* @return container protocol read chunk response
* @throws IOException if there is an I/O error while performing the call
*/
public static ContainerProtos.ReadChunkResponseProto readChunk(
XceiverClientSpi xceiverClient, ChunkInfo chunk, DatanodeBlockID blockID,
List<Validator> validators,
Token<? extends TokenIdentifier> token) throws IOException {
ReadChunkRequestProto.Builder readChunkRequest =
ReadChunkRequestProto.newBuilder()
.setBlockID(blockID)
.setChunkData(chunk)
.setReadChunkVersion(ContainerProtos.ReadChunkVersion.V1);
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder().setCmdType(Type.ReadChunk)
.setContainerID(blockID.getContainerID())
.setReadChunk(readChunkRequest);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
try (TracingUtil.TraceCloseable ignored = TracingUtil.createActivatedSpan("readChunk")) {
Span span = TracingUtil.getActiveSpan();
span.setAttribute("offset", chunk.getOffset())
.setAttribute("length", chunk.getLen())
.setAttribute("block", blockID.toString());
return tryEachDatanode(xceiverClient.getPipeline(),
d -> readChunk(xceiverClient, chunk, blockID,
validators, builder, d),
d -> toErrorMessage(chunk, blockID, d));
}
}
private static ContainerProtos.ReadChunkResponseProto readChunk(
XceiverClientSpi xceiverClient, ChunkInfo chunk, DatanodeBlockID blockID,
List<Validator> validators,
ContainerCommandRequestProto.Builder builder,
DatanodeDetails d) throws IOException {
ContainerCommandRequestProto.Builder requestBuilder = builder
.setDatanodeUuid(d.getUuidString());
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
requestBuilder = requestBuilder.setTraceID(traceId);
}
ContainerCommandResponseProto reply =
xceiverClient.sendCommand(requestBuilder.build(), validators);
final ReadChunkResponseProto response = reply.getReadChunk();
final long readLen = getLen(response);
if (readLen != chunk.getLen()) {
throw new IOException(toErrorMessage(chunk, blockID, d)
+ ": readLen=" + readLen);
}
return response;
}
static String toErrorMessage(ChunkInfo chunk, DatanodeBlockID blockId,
DatanodeDetails d) {
return String.format("Failed to read chunk %s (len=%s) %s from %s",
chunk.getChunkName(), chunk.getLen(), blockId, d);
}
static long getLen(ReadChunkResponseProto response) {
if (response.hasData()) {
return response.getData().size();
} else if (response.hasDataBuffers()) {
return response.getDataBuffers() .getBuffersList().stream()
.mapToLong(ByteString::size).sum();
} else {
return -1;
}
}
/**
* Calls the container protocol to write a chunk.
*
* @param xceiverClient client to perform call
* @param chunk information about chunk to write
* @param blockID ID of the block
* @param data the data of the chunk to write
* @param tokenString serialized block token
* @throws IOException if there is an I/O error while performing the call
*/
@SuppressWarnings("parameternumber")
public static XceiverClientReply writeChunkAsync(
XceiverClientSpi xceiverClient, ChunkInfo chunk, BlockID blockID,
ByteString data, String tokenString,
int replicationIndex, BlockData blockData, boolean close)
throws IOException, ExecutionException, InterruptedException {
WriteChunkRequestProto.Builder writeChunkRequest =
WriteChunkRequestProto.newBuilder()
.setBlockID(DatanodeBlockID.newBuilder()
.setContainerID(blockID.getContainerID())
.setLocalID(blockID.getLocalID())
.setBlockCommitSequenceId(blockID.getBlockCommitSequenceId())
.setReplicaIndex(replicationIndex)
.build())
.setChunkData(chunk)
.setData(data);
if (blockData != null) {
PutBlockRequestProto.Builder createBlockRequest =
PutBlockRequestProto.newBuilder()
.setBlockData(blockData)
.setEof(close);
writeChunkRequest.setBlock(createBlockRequest);
}
String id = xceiverClient.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder()
.setCmdType(Type.WriteChunk)
.setContainerID(blockID.getContainerID())
.setDatanodeUuid(id)
.setWriteChunk(writeChunkRequest);
if (tokenString != null) {
builder.setEncodedToken(tokenString);
}
ContainerCommandRequestProto request = builder.build();
return xceiverClient.sendCommandAsync(request);
}
/**
* Allows writing a small file using single RPC. This takes the container
* name, block name and data to write sends all that data to the container
* using a single RPC. This API is designed to be used for files which are
* smaller than 1 MB.
*
* @param client - client that communicates with the container.
* @param blockID - ID of the block
* @param data - Data to be written into the container.
* @param token a token for this block (may be null)
* @return container protocol writeSmallFile response
*/
public static PutSmallFileResponseProto writeSmallFile(
XceiverClientSpi client, BlockID blockID, byte[] data,
Token<OzoneBlockTokenIdentifier> token) throws IOException {
BlockData containerBlockData =
BlockData.newBuilder().setBlockID(blockID.getDatanodeBlockIDProtobuf())
.build();
PutBlockRequestProto.Builder createBlockRequest =
PutBlockRequestProto.newBuilder()
.setBlockData(containerBlockData);
KeyValue keyValue =
KeyValue.newBuilder().setKey("OverWriteRequested").setValue("true")
.build();
Checksum checksum = new Checksum(ChecksumType.CRC32, 256);
final ChecksumData checksumData = checksum.computeChecksum(data);
ChunkInfo chunk =
ChunkInfo.newBuilder()
.setChunkName(blockID.getLocalID() + "_chunk")
.setOffset(0)
.setLen(data.length)
.addMetadata(keyValue)
.setChecksumData(checksumData.getProtoBufMessage())
.build();
PutSmallFileRequestProto putSmallFileRequest =
PutSmallFileRequestProto.newBuilder().setChunkInfo(chunk)
.setBlock(createBlockRequest).setData(ByteString.copyFrom(data))
.build();
String id = client.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder =
ContainerCommandRequestProto.newBuilder()
.setCmdType(Type.PutSmallFile)
.setContainerID(blockID.getContainerID())
.setDatanodeUuid(id)
.setPutSmallFile(putSmallFileRequest);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
client.sendCommand(request, getValidatorList());
return response.getPutSmallFile();
}
/**
* createRecoveringContainer call that creates a container on the datanode.
* Currently this is used for EC reconstruction containers. When EC
* reconstruction coordinator reconstructing the containers, the in progress
* containers would be created as "RECOVERING" state containers.
* @param client - client
* @param containerID - ID of container
* @param encodedToken - encodedToken if security is enabled
* @param replicaIndex - index position of the container replica
*/
@InterfaceStability.Evolving
public static void createRecoveringContainer(XceiverClientSpi client,
long containerID, String encodedToken, int replicaIndex)
throws IOException {
createContainer(client, containerID, encodedToken,
ContainerProtos.ContainerDataProto.State.RECOVERING, replicaIndex);
}
/**
* createContainer call that creates a container on the datanode.
* @param client - client
* @param containerID - ID of container
* @param encodedToken - encodedToken if security is enabled
*/
public static void createContainer(XceiverClientSpi client, long containerID,
String encodedToken) throws IOException {
createContainer(client, containerID, encodedToken, null, 0);
}
/**
* createContainer call that creates a container on the datanode.
* @param client - client
* @param containerID - ID of container
* @param encodedToken - encodedToken if security is enabled
* @param state - state of the container
* @param replicaIndex - index position of the container replica
*/
public static void createContainer(XceiverClientSpi client,
long containerID, String encodedToken,
ContainerProtos.ContainerDataProto.State state, int replicaIndex)
throws IOException {
ContainerProtos.CreateContainerRequestProto.Builder createRequest =
ContainerProtos.CreateContainerRequestProto.newBuilder();
createRequest
.setContainerType(ContainerProtos.ContainerType.KeyValueContainer);
if (state != null) {
createRequest.setState(state);
}
if (replicaIndex > 0) {
createRequest.setReplicaIndex(replicaIndex);
}
String id = client.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder request =
ContainerCommandRequestProto.newBuilder();
if (encodedToken != null) {
request.setEncodedToken(encodedToken);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
request.setTraceID(traceId);
}
request.setCmdType(ContainerProtos.Type.CreateContainer);
request.setContainerID(containerID);
request.setCreateContainer(createRequest.build());
request.setDatanodeUuid(id);
client.sendCommand(request.build(), getValidatorList());
}
/**
* Deletes a container from a pipeline.
*
* @param force whether or not to forcibly delete the container.
* @param encodedToken - encodedToken if security is enabled
*/
public static void deleteContainer(XceiverClientSpi client, long containerID,
boolean force, String encodedToken) throws IOException {
ContainerProtos.DeleteContainerRequestProto.Builder deleteRequest =
ContainerProtos.DeleteContainerRequestProto.newBuilder();
deleteRequest.setForceDelete(force);
String id = client.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder request =
ContainerCommandRequestProto.newBuilder();
request.setCmdType(ContainerProtos.Type.DeleteContainer);
request.setContainerID(containerID);
request.setDeleteContainer(deleteRequest);
request.setDatanodeUuid(id);
if (encodedToken != null) {
request.setEncodedToken(encodedToken);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
request.setTraceID(traceId);
}
client.sendCommand(request.build(), getValidatorList());
}
/**
* Close a container.
*
* @param encodedToken - encodedToken if security is enabled
*/
public static void closeContainer(XceiverClientSpi client,
long containerID, String encodedToken)
throws IOException {
String id = client.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder request =
ContainerCommandRequestProto.newBuilder();
request.setCmdType(Type.CloseContainer);
request.setContainerID(containerID);
request.setCloseContainer(CloseContainerRequestProto.getDefaultInstance());
request.setDatanodeUuid(id);
if (encodedToken != null) {
request.setEncodedToken(encodedToken);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
request.setTraceID(traceId);
}
client.sendCommand(request.build(), getValidatorList());
}
/**
* readContainer call that gets meta data from an existing container.
*
* @param client - client
* @param encodedToken - encodedToken if security is enabled
*/
public static ReadContainerResponseProto readContainer(
XceiverClientSpi client, long containerID, String encodedToken)
throws IOException {
String id = client.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder request =
ContainerCommandRequestProto.newBuilder();
request.setCmdType(Type.ReadContainer);
request.setContainerID(containerID);
request.setReadContainer(ReadContainerRequestProto.getDefaultInstance());
request.setDatanodeUuid(id);
if (encodedToken != null) {
request.setEncodedToken(encodedToken);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
request.setTraceID(traceId);
}
ContainerCommandResponseProto response =
client.sendCommand(request.build(), getValidatorList());
return response.getReadContainer();
}
/**
* Reads the data given the blockID.
*
* @param blockID - ID of the block
* @param token a token for this block (may be null)
* @return GetSmallFileResponseProto
*/
public static GetSmallFileResponseProto readSmallFile(XceiverClientSpi client,
BlockID blockID,
Token<OzoneBlockTokenIdentifier> token) throws IOException {
GetBlockRequestProto.Builder getBlock = GetBlockRequestProto
.newBuilder()
.setBlockID(blockID.getDatanodeBlockIDProtobuf());
ContainerProtos.GetSmallFileRequestProto getSmallFileRequest =
GetSmallFileRequestProto
.newBuilder().setBlock(getBlock)
.setReadChunkVersion(ContainerProtos.ReadChunkVersion.V1)
.build();
String id = client.getPipeline().getClosestNode().getUuidString();
ContainerCommandRequestProto.Builder builder = ContainerCommandRequestProto
.newBuilder()
.setCmdType(Type.GetSmallFile)
.setContainerID(blockID.getContainerID())
.setDatanodeUuid(id)
.setGetSmallFile(getSmallFileRequest);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
client.sendCommand(request, getValidatorList());
return response.getGetSmallFile();
}
/**
* Send an echo to DataNode.
*
* @return EchoResponseProto
*/
public static EchoResponseProto echo(XceiverClientSpi client, String encodedContainerID,
long containerID, ByteString payloadReqBytes, int payloadRespSizeKB, int sleepTimeMs, boolean readOnly)
throws IOException {
ContainerProtos.EchoRequestProto getEcho =
EchoRequestProto
.newBuilder()
.setPayload(payloadReqBytes)
.setPayloadSizeResp(payloadRespSizeKB)
.setSleepTimeMs(sleepTimeMs)
.setReadOnly(readOnly)
.build();
String id = client.getPipeline().getClosestNode().getUuidString();
ContainerCommandRequestProto.Builder builder = ContainerCommandRequestProto
.newBuilder()
.setCmdType(Type.Echo)
.setContainerID(containerID)
.setDatanodeUuid(id)
.setEcho(getEcho);
if (!encodedContainerID.isEmpty()) {
builder.setEncodedToken(encodedContainerID);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response =
client.sendCommand(request, getValidatorList());
return response.getEcho();
}
/**
* Gets the container checksum info for a container from a datanode. This method does not deserialize the checksum
* info.
*
* @param client - client that communicates with the container
* @param containerID - Container Id of the container
* @param encodedContainerID - Encoded token if security is enabled
*
* @throws IOException For errors communicating with the datanode.
* @throws StorageContainerException For errors obtaining the checksum info, including the file being missing or
* empty on the datanode, or the datanode not having a replica of the container.
*/
public static ContainerProtos.GetContainerChecksumInfoResponseProto getContainerChecksumInfo(
XceiverClientSpi client, long containerID, String encodedContainerID) throws IOException {
ContainerProtos.GetContainerChecksumInfoRequestProto containerChecksumRequestProto =
ContainerProtos.GetContainerChecksumInfoRequestProto
.newBuilder()
.setContainerID(containerID)
.build();
String id = client.getPipeline().getClosestNode().getUuidString();
ContainerCommandRequestProto.Builder builder = ContainerCommandRequestProto
.newBuilder()
.setCmdType(Type.GetContainerChecksumInfo)
.setContainerID(containerID)
.setDatanodeUuid(id)
.setGetContainerChecksumInfo(containerChecksumRequestProto);
if (encodedContainerID != null) {
builder.setEncodedToken(encodedContainerID);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
ContainerCommandResponseProto response = client.sendCommand(request, getValidatorList());
return response.getGetContainerChecksumInfo();
}
/**
* Validates a response from a container protocol call. Any non-successful
* return code is mapped to a corresponding exception and thrown.
*
* @param response container protocol call response
* @throws StorageContainerException if the container protocol call failed
*/
public static void validateContainerResponse(
ContainerCommandResponseProto response
) throws StorageContainerException {
if (response.getResult() == ContainerProtos.Result.SUCCESS) {
return;
} else if (response.getResult()
== ContainerProtos.Result.BLOCK_NOT_COMMITTED) {
throw new BlockNotCommittedException(response.getMessage());
} else if (response.getResult()
== ContainerProtos.Result.CLOSED_CONTAINER_IO) {
throw new ContainerNotOpenException(response.getMessage());
}
throw new StorageContainerException(
response.getMessage(), response.getResult());
}
private static List<Validator> getValidatorList() {
return VALIDATORS;
}
private static List<Validator> createValidators() {
return singletonList(
(request, response) -> validateContainerResponse(response));
}
public static List<Validator> toValidatorList(Validator validator) {
final List<Validator> defaults = getValidatorList();
final List<Validator> validators
= new ArrayList<>(defaults.size() + 1);
validators.addAll(defaults);
validators.add(validator);
return Collections.unmodifiableList(validators);
}
public static HashMap<DatanodeDetails, GetBlockResponseProto>
getBlockFromAllNodes(
XceiverClientSpi xceiverClient,
DatanodeBlockID datanodeBlockID,
Token<OzoneBlockTokenIdentifier> token)
throws IOException, InterruptedException {
GetBlockRequestProto.Builder readBlockRequest = GetBlockRequestProto
.newBuilder()
.setBlockID(datanodeBlockID);
HashMap<DatanodeDetails, GetBlockResponseProto> datanodeToResponseMap
= new HashMap<>();
String id = xceiverClient.getPipeline().getFirstNode().getUuidString();
ContainerCommandRequestProto.Builder builder = ContainerCommandRequestProto
.newBuilder()
.setCmdType(Type.GetBlock)
.setContainerID(datanodeBlockID.getContainerID())
.setDatanodeUuid(id)
.setGetBlock(readBlockRequest);
if (token != null) {
builder.setEncodedToken(token.encodeToUrlString());
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
builder.setTraceID(traceId);
}
ContainerCommandRequestProto request = builder.build();
Map<DatanodeDetails, ContainerCommandResponseProto> responses =
xceiverClient.sendCommandOnAllNodes(request);
for (Map.Entry<DatanodeDetails, ContainerCommandResponseProto> entry:
responses.entrySet()) {
datanodeToResponseMap.put(entry.getKey(), entry.getValue().getGetBlock());
}
return datanodeToResponseMap;
}
public static HashMap<DatanodeDetails, ReadContainerResponseProto>
readContainerFromAllNodes(XceiverClientSpi client, long containerID,
String encodedToken) throws IOException, InterruptedException {
String id = client.getPipeline().getFirstNode().getUuidString();
HashMap<DatanodeDetails, ReadContainerResponseProto> datanodeToResponseMap
= new HashMap<>();
ContainerCommandRequestProto.Builder request =
ContainerCommandRequestProto.newBuilder();
request.setCmdType(Type.ReadContainer);
request.setContainerID(containerID);
request.setReadContainer(ReadContainerRequestProto.getDefaultInstance());
request.setDatanodeUuid(id);
if (encodedToken != null) {
request.setEncodedToken(encodedToken);
}
String traceId = TracingUtil.exportCurrentSpan();
if (traceId != null) {
request.setTraceID(traceId);
}
Map<DatanodeDetails, ContainerCommandResponseProto> responses =
client.sendCommandOnAllNodes(request.build());
for (Map.Entry<DatanodeDetails, ContainerCommandResponseProto> entry :
responses.entrySet()) {
datanodeToResponseMap.put(entry.getKey(),
entry.getValue().getReadContainer());
}
return datanodeToResponseMap;
}
}
|
googleapis/google-cloud-java | 37,857 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListOperatorsRequest.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/lva_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Message for requesting list of Operators.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListOperatorsRequest}
*/
public final class ListOperatorsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListOperatorsRequest)
ListOperatorsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListOperatorsRequest.newBuilder() to construct.
private ListOperatorsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListOperatorsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListOperatorsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListOperatorsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListOperatorsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListOperatorsRequest.class,
com.google.cloud.visionai.v1.ListOperatorsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.ListOperatorsRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ListOperatorsRequest other =
(com.google.cloud.visionai.v1.ListOperatorsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest 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.ListOperatorsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest 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.ListOperatorsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest 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.ListOperatorsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest 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.ListOperatorsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest 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.ListOperatorsRequest 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.ListOperatorsRequest 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.ListOperatorsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Operators.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListOperatorsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListOperatorsRequest)
com.google.cloud.visionai.v1.ListOperatorsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListOperatorsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListOperatorsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListOperatorsRequest.class,
com.google.cloud.visionai.v1.ListOperatorsRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ListOperatorsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.LvaServiceProto
.internal_static_google_cloud_visionai_v1_ListOperatorsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListOperatorsRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ListOperatorsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListOperatorsRequest build() {
com.google.cloud.visionai.v1.ListOperatorsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListOperatorsRequest buildPartial() {
com.google.cloud.visionai.v1.ListOperatorsRequest result =
new com.google.cloud.visionai.v1.ListOperatorsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.ListOperatorsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.ListOperatorsRequest) {
return mergeFrom((com.google.cloud.visionai.v1.ListOperatorsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ListOperatorsRequest other) {
if (other == com.google.cloud.visionai.v1.ListOperatorsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListOperatorsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListOperatorsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListOperatorsRequest)
private static final com.google.cloud.visionai.v1.ListOperatorsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListOperatorsRequest();
}
public static com.google.cloud.visionai.v1.ListOperatorsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListOperatorsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListOperatorsRequest>() {
@java.lang.Override
public ListOperatorsRequest 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<ListOperatorsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListOperatorsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListOperatorsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,029 | java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/RequestBasedSli.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/service.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* Service Level Indicators for which atomic units of service are counted
* directly.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.RequestBasedSli}
*/
public final class RequestBasedSli extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.RequestBasedSli)
RequestBasedSliOrBuilder {
private static final long serialVersionUID = 0L;
// Use RequestBasedSli.newBuilder() to construct.
private RequestBasedSli(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RequestBasedSli() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RequestBasedSli();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.ServiceMonitoringProto
.internal_static_google_monitoring_v3_RequestBasedSli_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.ServiceMonitoringProto
.internal_static_google_monitoring_v3_RequestBasedSli_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.RequestBasedSli.class,
com.google.monitoring.v3.RequestBasedSli.Builder.class);
}
private int methodCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object method_;
public enum MethodCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
GOOD_TOTAL_RATIO(1),
DISTRIBUTION_CUT(3),
METHOD_NOT_SET(0);
private final int value;
private MethodCase(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 MethodCase valueOf(int value) {
return forNumber(value);
}
public static MethodCase forNumber(int value) {
switch (value) {
case 1:
return GOOD_TOTAL_RATIO;
case 3:
return DISTRIBUTION_CUT;
case 0:
return METHOD_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public MethodCase getMethodCase() {
return MethodCase.forNumber(methodCase_);
}
public static final int GOOD_TOTAL_RATIO_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*
* @return Whether the goodTotalRatio field is set.
*/
@java.lang.Override
public boolean hasGoodTotalRatio() {
return methodCase_ == 1;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*
* @return The goodTotalRatio.
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesRatio getGoodTotalRatio() {
if (methodCase_ == 1) {
return (com.google.monitoring.v3.TimeSeriesRatio) method_;
}
return com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesRatioOrBuilder getGoodTotalRatioOrBuilder() {
if (methodCase_ == 1) {
return (com.google.monitoring.v3.TimeSeriesRatio) method_;
}
return com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
}
public static final int DISTRIBUTION_CUT_FIELD_NUMBER = 3;
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*
* @return Whether the distributionCut field is set.
*/
@java.lang.Override
public boolean hasDistributionCut() {
return methodCase_ == 3;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*
* @return The distributionCut.
*/
@java.lang.Override
public com.google.monitoring.v3.DistributionCut getDistributionCut() {
if (methodCase_ == 3) {
return (com.google.monitoring.v3.DistributionCut) method_;
}
return com.google.monitoring.v3.DistributionCut.getDefaultInstance();
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.DistributionCutOrBuilder getDistributionCutOrBuilder() {
if (methodCase_ == 3) {
return (com.google.monitoring.v3.DistributionCut) method_;
}
return com.google.monitoring.v3.DistributionCut.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 (methodCase_ == 1) {
output.writeMessage(1, (com.google.monitoring.v3.TimeSeriesRatio) method_);
}
if (methodCase_ == 3) {
output.writeMessage(3, (com.google.monitoring.v3.DistributionCut) method_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (methodCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.monitoring.v3.TimeSeriesRatio) method_);
}
if (methodCase_ == 3) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
3, (com.google.monitoring.v3.DistributionCut) method_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.RequestBasedSli)) {
return super.equals(obj);
}
com.google.monitoring.v3.RequestBasedSli other = (com.google.monitoring.v3.RequestBasedSli) obj;
if (!getMethodCase().equals(other.getMethodCase())) return false;
switch (methodCase_) {
case 1:
if (!getGoodTotalRatio().equals(other.getGoodTotalRatio())) return false;
break;
case 3:
if (!getDistributionCut().equals(other.getDistributionCut())) 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 (methodCase_) {
case 1:
hash = (37 * hash) + GOOD_TOTAL_RATIO_FIELD_NUMBER;
hash = (53 * hash) + getGoodTotalRatio().hashCode();
break;
case 3:
hash = (37 * hash) + DISTRIBUTION_CUT_FIELD_NUMBER;
hash = (53 * hash) + getDistributionCut().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.RequestBasedSli parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.RequestBasedSli parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.RequestBasedSli parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.RequestBasedSli 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>
* Service Level Indicators for which atomic units of service are counted
* directly.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.RequestBasedSli}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.RequestBasedSli)
com.google.monitoring.v3.RequestBasedSliOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.ServiceMonitoringProto
.internal_static_google_monitoring_v3_RequestBasedSli_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.ServiceMonitoringProto
.internal_static_google_monitoring_v3_RequestBasedSli_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.RequestBasedSli.class,
com.google.monitoring.v3.RequestBasedSli.Builder.class);
}
// Construct using com.google.monitoring.v3.RequestBasedSli.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (goodTotalRatioBuilder_ != null) {
goodTotalRatioBuilder_.clear();
}
if (distributionCutBuilder_ != null) {
distributionCutBuilder_.clear();
}
methodCase_ = 0;
method_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.ServiceMonitoringProto
.internal_static_google_monitoring_v3_RequestBasedSli_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.RequestBasedSli getDefaultInstanceForType() {
return com.google.monitoring.v3.RequestBasedSli.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.RequestBasedSli build() {
com.google.monitoring.v3.RequestBasedSli result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.RequestBasedSli buildPartial() {
com.google.monitoring.v3.RequestBasedSli result =
new com.google.monitoring.v3.RequestBasedSli(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.monitoring.v3.RequestBasedSli result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.monitoring.v3.RequestBasedSli result) {
result.methodCase_ = methodCase_;
result.method_ = this.method_;
if (methodCase_ == 1 && goodTotalRatioBuilder_ != null) {
result.method_ = goodTotalRatioBuilder_.build();
}
if (methodCase_ == 3 && distributionCutBuilder_ != null) {
result.method_ = distributionCutBuilder_.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.monitoring.v3.RequestBasedSli) {
return mergeFrom((com.google.monitoring.v3.RequestBasedSli) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.RequestBasedSli other) {
if (other == com.google.monitoring.v3.RequestBasedSli.getDefaultInstance()) return this;
switch (other.getMethodCase()) {
case GOOD_TOTAL_RATIO:
{
mergeGoodTotalRatio(other.getGoodTotalRatio());
break;
}
case DISTRIBUTION_CUT:
{
mergeDistributionCut(other.getDistributionCut());
break;
}
case METHOD_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getGoodTotalRatioFieldBuilder().getBuilder(), extensionRegistry);
methodCase_ = 1;
break;
} // case 10
case 26:
{
input.readMessage(getDistributionCutFieldBuilder().getBuilder(), extensionRegistry);
methodCase_ = 3;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int methodCase_ = 0;
private java.lang.Object method_;
public MethodCase getMethodCase() {
return MethodCase.forNumber(methodCase_);
}
public Builder clearMethod() {
methodCase_ = 0;
method_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesRatio,
com.google.monitoring.v3.TimeSeriesRatio.Builder,
com.google.monitoring.v3.TimeSeriesRatioOrBuilder>
goodTotalRatioBuilder_;
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*
* @return Whether the goodTotalRatio field is set.
*/
@java.lang.Override
public boolean hasGoodTotalRatio() {
return methodCase_ == 1;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*
* @return The goodTotalRatio.
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesRatio getGoodTotalRatio() {
if (goodTotalRatioBuilder_ == null) {
if (methodCase_ == 1) {
return (com.google.monitoring.v3.TimeSeriesRatio) method_;
}
return com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
} else {
if (methodCase_ == 1) {
return goodTotalRatioBuilder_.getMessage();
}
return com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
}
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
public Builder setGoodTotalRatio(com.google.monitoring.v3.TimeSeriesRatio value) {
if (goodTotalRatioBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
method_ = value;
onChanged();
} else {
goodTotalRatioBuilder_.setMessage(value);
}
methodCase_ = 1;
return this;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
public Builder setGoodTotalRatio(
com.google.monitoring.v3.TimeSeriesRatio.Builder builderForValue) {
if (goodTotalRatioBuilder_ == null) {
method_ = builderForValue.build();
onChanged();
} else {
goodTotalRatioBuilder_.setMessage(builderForValue.build());
}
methodCase_ = 1;
return this;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
public Builder mergeGoodTotalRatio(com.google.monitoring.v3.TimeSeriesRatio value) {
if (goodTotalRatioBuilder_ == null) {
if (methodCase_ == 1
&& method_ != com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance()) {
method_ =
com.google.monitoring.v3.TimeSeriesRatio.newBuilder(
(com.google.monitoring.v3.TimeSeriesRatio) method_)
.mergeFrom(value)
.buildPartial();
} else {
method_ = value;
}
onChanged();
} else {
if (methodCase_ == 1) {
goodTotalRatioBuilder_.mergeFrom(value);
} else {
goodTotalRatioBuilder_.setMessage(value);
}
}
methodCase_ = 1;
return this;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
public Builder clearGoodTotalRatio() {
if (goodTotalRatioBuilder_ == null) {
if (methodCase_ == 1) {
methodCase_ = 0;
method_ = null;
onChanged();
}
} else {
if (methodCase_ == 1) {
methodCase_ = 0;
method_ = null;
}
goodTotalRatioBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
public com.google.monitoring.v3.TimeSeriesRatio.Builder getGoodTotalRatioBuilder() {
return getGoodTotalRatioFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesRatioOrBuilder getGoodTotalRatioOrBuilder() {
if ((methodCase_ == 1) && (goodTotalRatioBuilder_ != null)) {
return goodTotalRatioBuilder_.getMessageOrBuilder();
} else {
if (methodCase_ == 1) {
return (com.google.monitoring.v3.TimeSeriesRatio) method_;
}
return com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
}
}
/**
*
*
* <pre>
* `good_total_ratio` is used when the ratio of `good_service` to
* `total_service` is computed from two `TimeSeries`.
* </pre>
*
* <code>.google.monitoring.v3.TimeSeriesRatio good_total_ratio = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesRatio,
com.google.monitoring.v3.TimeSeriesRatio.Builder,
com.google.monitoring.v3.TimeSeriesRatioOrBuilder>
getGoodTotalRatioFieldBuilder() {
if (goodTotalRatioBuilder_ == null) {
if (!(methodCase_ == 1)) {
method_ = com.google.monitoring.v3.TimeSeriesRatio.getDefaultInstance();
}
goodTotalRatioBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesRatio,
com.google.monitoring.v3.TimeSeriesRatio.Builder,
com.google.monitoring.v3.TimeSeriesRatioOrBuilder>(
(com.google.monitoring.v3.TimeSeriesRatio) method_,
getParentForChildren(),
isClean());
method_ = null;
}
methodCase_ = 1;
onChanged();
return goodTotalRatioBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.DistributionCut,
com.google.monitoring.v3.DistributionCut.Builder,
com.google.monitoring.v3.DistributionCutOrBuilder>
distributionCutBuilder_;
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*
* @return Whether the distributionCut field is set.
*/
@java.lang.Override
public boolean hasDistributionCut() {
return methodCase_ == 3;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*
* @return The distributionCut.
*/
@java.lang.Override
public com.google.monitoring.v3.DistributionCut getDistributionCut() {
if (distributionCutBuilder_ == null) {
if (methodCase_ == 3) {
return (com.google.monitoring.v3.DistributionCut) method_;
}
return com.google.monitoring.v3.DistributionCut.getDefaultInstance();
} else {
if (methodCase_ == 3) {
return distributionCutBuilder_.getMessage();
}
return com.google.monitoring.v3.DistributionCut.getDefaultInstance();
}
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
public Builder setDistributionCut(com.google.monitoring.v3.DistributionCut value) {
if (distributionCutBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
method_ = value;
onChanged();
} else {
distributionCutBuilder_.setMessage(value);
}
methodCase_ = 3;
return this;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
public Builder setDistributionCut(
com.google.monitoring.v3.DistributionCut.Builder builderForValue) {
if (distributionCutBuilder_ == null) {
method_ = builderForValue.build();
onChanged();
} else {
distributionCutBuilder_.setMessage(builderForValue.build());
}
methodCase_ = 3;
return this;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
public Builder mergeDistributionCut(com.google.monitoring.v3.DistributionCut value) {
if (distributionCutBuilder_ == null) {
if (methodCase_ == 3
&& method_ != com.google.monitoring.v3.DistributionCut.getDefaultInstance()) {
method_ =
com.google.monitoring.v3.DistributionCut.newBuilder(
(com.google.monitoring.v3.DistributionCut) method_)
.mergeFrom(value)
.buildPartial();
} else {
method_ = value;
}
onChanged();
} else {
if (methodCase_ == 3) {
distributionCutBuilder_.mergeFrom(value);
} else {
distributionCutBuilder_.setMessage(value);
}
}
methodCase_ = 3;
return this;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
public Builder clearDistributionCut() {
if (distributionCutBuilder_ == null) {
if (methodCase_ == 3) {
methodCase_ = 0;
method_ = null;
onChanged();
}
} else {
if (methodCase_ == 3) {
methodCase_ = 0;
method_ = null;
}
distributionCutBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
public com.google.monitoring.v3.DistributionCut.Builder getDistributionCutBuilder() {
return getDistributionCutFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.DistributionCutOrBuilder getDistributionCutOrBuilder() {
if ((methodCase_ == 3) && (distributionCutBuilder_ != null)) {
return distributionCutBuilder_.getMessageOrBuilder();
} else {
if (methodCase_ == 3) {
return (com.google.monitoring.v3.DistributionCut) method_;
}
return com.google.monitoring.v3.DistributionCut.getDefaultInstance();
}
}
/**
*
*
* <pre>
* `distribution_cut` is used when `good_service` is a count of values
* aggregated in a `Distribution` that fall into a good range. The
* `total_service` is the total count of all values aggregated in the
* `Distribution`.
* </pre>
*
* <code>.google.monitoring.v3.DistributionCut distribution_cut = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.DistributionCut,
com.google.monitoring.v3.DistributionCut.Builder,
com.google.monitoring.v3.DistributionCutOrBuilder>
getDistributionCutFieldBuilder() {
if (distributionCutBuilder_ == null) {
if (!(methodCase_ == 3)) {
method_ = com.google.monitoring.v3.DistributionCut.getDefaultInstance();
}
distributionCutBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.DistributionCut,
com.google.monitoring.v3.DistributionCut.Builder,
com.google.monitoring.v3.DistributionCutOrBuilder>(
(com.google.monitoring.v3.DistributionCut) method_,
getParentForChildren(),
isClean());
method_ = null;
}
methodCase_ = 3;
onChanged();
return distributionCutBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.RequestBasedSli)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.RequestBasedSli)
private static final com.google.monitoring.v3.RequestBasedSli DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.RequestBasedSli();
}
public static com.google.monitoring.v3.RequestBasedSli getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RequestBasedSli> PARSER =
new com.google.protobuf.AbstractParser<RequestBasedSli>() {
@java.lang.Override
public RequestBasedSli 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<RequestBasedSli> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RequestBasedSli> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.RequestBasedSli getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,027 | java-billing/proto-google-cloud-billing-v1/src/main/java/com/google/cloud/billing/v1/ListBillingAccountsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/billing/v1/cloud_billing.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.billing.v1;
/**
*
*
* <pre>
* Response message for `ListBillingAccounts`.
* </pre>
*
* Protobuf type {@code google.cloud.billing.v1.ListBillingAccountsResponse}
*/
public final class ListBillingAccountsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.billing.v1.ListBillingAccountsResponse)
ListBillingAccountsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListBillingAccountsResponse.newBuilder() to construct.
private ListBillingAccountsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListBillingAccountsResponse() {
billingAccounts_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListBillingAccountsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.v1.CloudBillingProto
.internal_static_google_cloud_billing_v1_ListBillingAccountsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.v1.CloudBillingProto
.internal_static_google_cloud_billing_v1_ListBillingAccountsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.v1.ListBillingAccountsResponse.class,
com.google.cloud.billing.v1.ListBillingAccountsResponse.Builder.class);
}
public static final int BILLING_ACCOUNTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.billing.v1.BillingAccount> billingAccounts_;
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.billing.v1.BillingAccount> getBillingAccountsList() {
return billingAccounts_;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.billing.v1.BillingAccountOrBuilder>
getBillingAccountsOrBuilderList() {
return billingAccounts_;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
@java.lang.Override
public int getBillingAccountsCount() {
return billingAccounts_.size();
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
@java.lang.Override
public com.google.cloud.billing.v1.BillingAccount getBillingAccounts(int index) {
return billingAccounts_.get(index);
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
@java.lang.Override
public com.google.cloud.billing.v1.BillingAccountOrBuilder getBillingAccountsOrBuilder(
int index) {
return billingAccounts_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </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 < billingAccounts_.size(); i++) {
output.writeMessage(1, billingAccounts_.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 < billingAccounts_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, billingAccounts_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.billing.v1.ListBillingAccountsResponse)) {
return super.equals(obj);
}
com.google.cloud.billing.v1.ListBillingAccountsResponse other =
(com.google.cloud.billing.v1.ListBillingAccountsResponse) obj;
if (!getBillingAccountsList().equals(other.getBillingAccountsList())) 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 (getBillingAccountsCount() > 0) {
hash = (37 * hash) + BILLING_ACCOUNTS_FIELD_NUMBER;
hash = (53 * hash) + getBillingAccountsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.billing.v1.ListBillingAccountsResponse 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 `ListBillingAccounts`.
* </pre>
*
* Protobuf type {@code google.cloud.billing.v1.ListBillingAccountsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.billing.v1.ListBillingAccountsResponse)
com.google.cloud.billing.v1.ListBillingAccountsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.billing.v1.CloudBillingProto
.internal_static_google_cloud_billing_v1_ListBillingAccountsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.billing.v1.CloudBillingProto
.internal_static_google_cloud_billing_v1_ListBillingAccountsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.billing.v1.ListBillingAccountsResponse.class,
com.google.cloud.billing.v1.ListBillingAccountsResponse.Builder.class);
}
// Construct using com.google.cloud.billing.v1.ListBillingAccountsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (billingAccountsBuilder_ == null) {
billingAccounts_ = java.util.Collections.emptyList();
} else {
billingAccounts_ = null;
billingAccountsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.billing.v1.CloudBillingProto
.internal_static_google_cloud_billing_v1_ListBillingAccountsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.billing.v1.ListBillingAccountsResponse getDefaultInstanceForType() {
return com.google.cloud.billing.v1.ListBillingAccountsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.billing.v1.ListBillingAccountsResponse build() {
com.google.cloud.billing.v1.ListBillingAccountsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.billing.v1.ListBillingAccountsResponse buildPartial() {
com.google.cloud.billing.v1.ListBillingAccountsResponse result =
new com.google.cloud.billing.v1.ListBillingAccountsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.billing.v1.ListBillingAccountsResponse result) {
if (billingAccountsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
billingAccounts_ = java.util.Collections.unmodifiableList(billingAccounts_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.billingAccounts_ = billingAccounts_;
} else {
result.billingAccounts_ = billingAccountsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.billing.v1.ListBillingAccountsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.billing.v1.ListBillingAccountsResponse) {
return mergeFrom((com.google.cloud.billing.v1.ListBillingAccountsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.billing.v1.ListBillingAccountsResponse other) {
if (other == com.google.cloud.billing.v1.ListBillingAccountsResponse.getDefaultInstance())
return this;
if (billingAccountsBuilder_ == null) {
if (!other.billingAccounts_.isEmpty()) {
if (billingAccounts_.isEmpty()) {
billingAccounts_ = other.billingAccounts_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureBillingAccountsIsMutable();
billingAccounts_.addAll(other.billingAccounts_);
}
onChanged();
}
} else {
if (!other.billingAccounts_.isEmpty()) {
if (billingAccountsBuilder_.isEmpty()) {
billingAccountsBuilder_.dispose();
billingAccountsBuilder_ = null;
billingAccounts_ = other.billingAccounts_;
bitField0_ = (bitField0_ & ~0x00000001);
billingAccountsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getBillingAccountsFieldBuilder()
: null;
} else {
billingAccountsBuilder_.addAllMessages(other.billingAccounts_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.billing.v1.BillingAccount m =
input.readMessage(
com.google.cloud.billing.v1.BillingAccount.parser(), extensionRegistry);
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
billingAccounts_.add(m);
} else {
billingAccountsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.billing.v1.BillingAccount> billingAccounts_ =
java.util.Collections.emptyList();
private void ensureBillingAccountsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
billingAccounts_ =
new java.util.ArrayList<com.google.cloud.billing.v1.BillingAccount>(billingAccounts_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.v1.BillingAccount,
com.google.cloud.billing.v1.BillingAccount.Builder,
com.google.cloud.billing.v1.BillingAccountOrBuilder>
billingAccountsBuilder_;
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public java.util.List<com.google.cloud.billing.v1.BillingAccount> getBillingAccountsList() {
if (billingAccountsBuilder_ == null) {
return java.util.Collections.unmodifiableList(billingAccounts_);
} else {
return billingAccountsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public int getBillingAccountsCount() {
if (billingAccountsBuilder_ == null) {
return billingAccounts_.size();
} else {
return billingAccountsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public com.google.cloud.billing.v1.BillingAccount getBillingAccounts(int index) {
if (billingAccountsBuilder_ == null) {
return billingAccounts_.get(index);
} else {
return billingAccountsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder setBillingAccounts(int index, com.google.cloud.billing.v1.BillingAccount value) {
if (billingAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBillingAccountsIsMutable();
billingAccounts_.set(index, value);
onChanged();
} else {
billingAccountsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder setBillingAccounts(
int index, com.google.cloud.billing.v1.BillingAccount.Builder builderForValue) {
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
billingAccounts_.set(index, builderForValue.build());
onChanged();
} else {
billingAccountsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder addBillingAccounts(com.google.cloud.billing.v1.BillingAccount value) {
if (billingAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBillingAccountsIsMutable();
billingAccounts_.add(value);
onChanged();
} else {
billingAccountsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder addBillingAccounts(int index, com.google.cloud.billing.v1.BillingAccount value) {
if (billingAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureBillingAccountsIsMutable();
billingAccounts_.add(index, value);
onChanged();
} else {
billingAccountsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder addBillingAccounts(
com.google.cloud.billing.v1.BillingAccount.Builder builderForValue) {
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
billingAccounts_.add(builderForValue.build());
onChanged();
} else {
billingAccountsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder addBillingAccounts(
int index, com.google.cloud.billing.v1.BillingAccount.Builder builderForValue) {
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
billingAccounts_.add(index, builderForValue.build());
onChanged();
} else {
billingAccountsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder addAllBillingAccounts(
java.lang.Iterable<? extends com.google.cloud.billing.v1.BillingAccount> values) {
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, billingAccounts_);
onChanged();
} else {
billingAccountsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder clearBillingAccounts() {
if (billingAccountsBuilder_ == null) {
billingAccounts_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
billingAccountsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public Builder removeBillingAccounts(int index) {
if (billingAccountsBuilder_ == null) {
ensureBillingAccountsIsMutable();
billingAccounts_.remove(index);
onChanged();
} else {
billingAccountsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public com.google.cloud.billing.v1.BillingAccount.Builder getBillingAccountsBuilder(int index) {
return getBillingAccountsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public com.google.cloud.billing.v1.BillingAccountOrBuilder getBillingAccountsOrBuilder(
int index) {
if (billingAccountsBuilder_ == null) {
return billingAccounts_.get(index);
} else {
return billingAccountsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public java.util.List<? extends com.google.cloud.billing.v1.BillingAccountOrBuilder>
getBillingAccountsOrBuilderList() {
if (billingAccountsBuilder_ != null) {
return billingAccountsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(billingAccounts_);
}
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public com.google.cloud.billing.v1.BillingAccount.Builder addBillingAccountsBuilder() {
return getBillingAccountsFieldBuilder()
.addBuilder(com.google.cloud.billing.v1.BillingAccount.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public com.google.cloud.billing.v1.BillingAccount.Builder addBillingAccountsBuilder(int index) {
return getBillingAccountsFieldBuilder()
.addBuilder(index, com.google.cloud.billing.v1.BillingAccount.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of billing accounts.
* </pre>
*
* <code>repeated .google.cloud.billing.v1.BillingAccount billing_accounts = 1;</code>
*/
public java.util.List<com.google.cloud.billing.v1.BillingAccount.Builder>
getBillingAccountsBuilderList() {
return getBillingAccountsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.v1.BillingAccount,
com.google.cloud.billing.v1.BillingAccount.Builder,
com.google.cloud.billing.v1.BillingAccountOrBuilder>
getBillingAccountsFieldBuilder() {
if (billingAccountsBuilder_ == null) {
billingAccountsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.billing.v1.BillingAccount,
com.google.cloud.billing.v1.BillingAccount.Builder,
com.google.cloud.billing.v1.BillingAccountOrBuilder>(
billingAccounts_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
billingAccounts_ = null;
}
return billingAccountsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve the next page of results. To retrieve the next page,
* call `ListBillingAccounts` again with the `page_token` field set to this
* value. This field is empty if there are no more results to retrieve.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.billing.v1.ListBillingAccountsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.billing.v1.ListBillingAccountsResponse)
private static final com.google.cloud.billing.v1.ListBillingAccountsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.billing.v1.ListBillingAccountsResponse();
}
public static com.google.cloud.billing.v1.ListBillingAccountsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListBillingAccountsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListBillingAccountsResponse>() {
@java.lang.Override
public ListBillingAccountsResponse 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<ListBillingAccountsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListBillingAccountsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.billing.v1.ListBillingAccountsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/rocketmq | 38,434 | broker/src/main/java/org/apache/rocketmq/broker/pop/PopConsumerService.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.rocketmq.broker.pop;
import com.alibaba.fastjson.JSON;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.KeyBuilder;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.ServiceThread;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.common.TopicFilterType;
import org.apache.rocketmq.common.constant.ConsumeInitMode;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.common.message.MessageAccessor;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.message.MessageDecoder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageExtBrokerInner;
import org.apache.rocketmq.common.utils.ConcurrentHashMapUtils;
import org.apache.rocketmq.remoting.protocol.header.ExtraInfoUtil;
import org.apache.rocketmq.store.AppendMessageStatus;
import org.apache.rocketmq.store.GetMessageResult;
import org.apache.rocketmq.store.GetMessageStatus;
import org.apache.rocketmq.store.MessageFilter;
import org.apache.rocketmq.store.PutMessageResult;
import org.apache.rocketmq.store.SelectMappedBufferResult;
import org.apache.rocketmq.store.exception.ConsumeQueueException;
import org.apache.rocketmq.store.pop.PopCheckPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PopConsumerService extends ServiceThread {
private static final Logger log = LoggerFactory.getLogger(LoggerName.ROCKETMQ_POP_LOGGER_NAME);
private static final long OFFSET_NOT_EXIST = -1L;
private static final String ROCKSDB_DIRECTORY = "kvStore";
private static final int[] REWRITE_INTERVALS_IN_SECONDS =
new int[] {10, 30, 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 1200, 1800, 3600, 7200};
private final AtomicBoolean consumerRunning;
private final BrokerConfig brokerConfig;
private final BrokerController brokerController;
private final AtomicLong currentTime;
private final AtomicLong lastCleanupLockTime;
private final PopConsumerCache popConsumerCache;
private final PopConsumerKVStore popConsumerStore;
private final PopConsumerLockService consumerLockService;
private final ConcurrentMap<String /* groupId@topicId*/, AtomicLong> requestCountTable;
public PopConsumerService(BrokerController brokerController) {
this.brokerController = brokerController;
this.brokerConfig = brokerController.getBrokerConfig();
this.consumerRunning = new AtomicBoolean(false);
this.requestCountTable = new ConcurrentHashMap<>();
this.currentTime = new AtomicLong(TimeUnit.SECONDS.toMillis(3));
this.lastCleanupLockTime = new AtomicLong(System.currentTimeMillis());
this.consumerLockService = new PopConsumerLockService(TimeUnit.MINUTES.toMillis(2));
this.popConsumerStore = new PopConsumerRocksdbStore(Paths.get(
brokerController.getMessageStoreConfig().getStorePathRootDir(), ROCKSDB_DIRECTORY).toString());
this.popConsumerCache = brokerConfig.isEnablePopBufferMerge() ? new PopConsumerCache(
brokerController, this.popConsumerStore, this.consumerLockService, this::revive) : null;
log.info("PopConsumerService init, buffer={}, rocksdb filePath={}",
brokerConfig.isEnablePopBufferMerge(), this.popConsumerStore.getFilePath());
}
/**
* In-flight messages are those that have been received from a queue
* by a consumer but have not yet been deleted. For standard queues,
* there is a limit on the number of in-flight messages, depending on queue traffic and message backlog.
*/
public boolean isPopShouldStop(String group, String topic, int queueId) {
return brokerConfig.isEnablePopMessageThreshold() && popConsumerCache != null &&
popConsumerCache.getPopInFlightMessageCount(group, topic, queueId) >=
brokerConfig.getPopInflightMessageThreshold();
}
public long getPendingFilterCount(String groupId, String topicId, int queueId) {
try {
long maxOffset = this.brokerController.getMessageStore().getMaxOffsetInQueue(topicId, queueId);
long consumeOffset = this.brokerController.getConsumerOffsetManager().queryOffset(groupId, topicId, queueId);
return maxOffset - consumeOffset;
} catch (ConsumeQueueException e) {
throw new RuntimeException(e);
}
}
public GetMessageResult recodeRetryMessage(GetMessageResult getMessageResult,
String topicId, long offset, long popTime, long invisibleTime) {
if (getMessageResult.getMessageCount() == 0 ||
getMessageResult.getMessageMapedList().isEmpty()) {
return getMessageResult;
}
GetMessageResult result = new GetMessageResult(getMessageResult.getMessageCount());
result.setStatus(GetMessageStatus.FOUND);
String brokerName = brokerConfig.getBrokerName();
for (SelectMappedBufferResult bufferResult : getMessageResult.getMessageMapedList()) {
List<MessageExt> messageExtList = MessageDecoder.decodesBatch(
bufferResult.getByteBuffer(), true, false, true);
bufferResult.release();
for (MessageExt messageExt : messageExtList) {
try {
// When override retry message topic to origin topic,
// need clear message store size to recode
String ckInfo = ExtraInfoUtil.buildExtraInfo(offset, popTime, invisibleTime, 0,
messageExt.getTopic(), brokerName, messageExt.getQueueId(), messageExt.getQueueOffset());
messageExt.getProperties().putIfAbsent(MessageConst.PROPERTY_POP_CK, ckInfo);
messageExt.setTopic(topicId);
messageExt.setStoreSize(0);
byte[] encode = MessageDecoder.encode(messageExt, false);
ByteBuffer buffer = ByteBuffer.wrap(encode);
SelectMappedBufferResult tmpResult = new SelectMappedBufferResult(
bufferResult.getStartOffset(), buffer, encode.length, null);
result.addMessage(tmpResult);
} catch (Exception e) {
log.error("PopConsumerService exception in recode retry message, topic={}", topicId, e);
}
}
}
return result;
}
public PopConsumerContext handleGetMessageResult(PopConsumerContext context, GetMessageResult result,
String topicId, int queueId, PopConsumerRecord.RetryType retryType, long offset) {
if (GetMessageStatus.FOUND.equals(result.getStatus()) && !result.getMessageQueueOffset().isEmpty()) {
if (context.isFifo()) {
this.setFifoBlocked(context, context.getGroupId(), topicId, queueId, result.getMessageQueueOffset());
}
// build response header here
context.addGetMessageResult(result, topicId, queueId, retryType, offset);
if (brokerConfig.isPopConsumerKVServiceLog()) {
log.info("PopConsumerService pop, time={}, invisible={}, " +
"groupId={}, topic={}, queueId={}, offset={}, attemptId={}",
context.getPopTime(), context.getInvisibleTime(), context.getGroupId(),
topicId, queueId, result.getMessageQueueOffset(), context.getAttemptId());
}
}
long commitOffset = offset;
if (context.isFifo()) {
if (!GetMessageStatus.FOUND.equals(result.getStatus())) {
commitOffset = result.getNextBeginOffset();
}
} else {
this.brokerController.getConsumerOffsetManager().commitPullOffset(
context.getClientHost(), context.getGroupId(), topicId, queueId, result.getNextBeginOffset());
if (brokerConfig.isEnablePopBufferMerge() && popConsumerCache != null) {
long minOffset = popConsumerCache.getMinOffsetInCache(context.getGroupId(), topicId, queueId);
if (minOffset != OFFSET_NOT_EXIST) {
commitOffset = minOffset;
}
}
}
this.brokerController.getConsumerOffsetManager().commitOffset(
context.getClientHost(), context.getGroupId(), topicId, queueId, commitOffset);
return context;
}
public long getPopOffset(String groupId, String topicId, int queueId, int initMode, boolean fifo) {
// For FIFO messages, the pull offset is not used.
// This preserves compatibility when switching from pull consumer to pop consumer.
long offset = fifo ?
this.brokerController.getConsumerOffsetManager().queryOffset(groupId, topicId, queueId) :
this.brokerController.getConsumerOffsetManager().queryPullOffset(groupId, topicId, queueId);
if (offset < 0L) {
try {
offset = this.brokerController.getPopMessageProcessor()
.getInitOffset(topicId, groupId, queueId, initMode, true);
log.info("PopConsumerService init offset, groupId={}, topicId={}, queueId={}, init={}, offset={}",
groupId, topicId, queueId, ConsumeInitMode.MIN == initMode ? "min" : "max", offset);
} catch (ConsumeQueueException e) {
throw new RuntimeException(e);
}
}
Long resetOffset =
this.brokerController.getConsumerOffsetManager().queryThenEraseResetOffset(topicId, groupId, queueId);
if (resetOffset != null) {
this.clearCache(groupId, topicId, queueId);
this.brokerController.getConsumerOrderInfoManager().clearBlock(topicId, groupId, queueId);
this.brokerController.getConsumerOffsetManager()
.commitOffset("ResetPopOffset", groupId, topicId, queueId, resetOffset);
}
return resetOffset != null ? resetOffset : offset;
}
public CompletableFuture<GetMessageResult> getMessageAsync(String clientHost,
String groupId, String topicId, int queueId, long offset, int batchSize, MessageFilter filter) {
log.debug("PopConsumerService getMessageAsync, groupId={}, topicId={}, queueId={}, offset={}, batchSize={}, filter={}",
groupId, topicId, offset, queueId, batchSize, filter != null);
CompletableFuture<GetMessageResult> getMessageFuture =
brokerController.getMessageStore().getMessageAsync(groupId, topicId, queueId, offset, batchSize, filter);
// refer org.apache.rocketmq.broker.processor.PopMessageProcessor#popMsgFromQueue
return getMessageFuture.thenCompose(result -> {
if (result == null) {
return CompletableFuture.completedFuture(null);
}
// maybe store offset is not correct.
if (GetMessageStatus.OFFSET_TOO_SMALL.equals(result.getStatus()) ||
GetMessageStatus.OFFSET_OVERFLOW_BADLY.equals(result.getStatus()) ||
GetMessageStatus.OFFSET_FOUND_NULL.equals(result.getStatus())) {
// commit offset, because the offset is not correct
// If offset in store is greater than cq offset, it will cause duplicate messages,
// because offset in PopBuffer is not committed.
this.brokerController.getConsumerOffsetManager().commitOffset(
clientHost, groupId, topicId, queueId, result.getNextBeginOffset());
log.warn("PopConsumerService getMessageAsync, initial offset because store is no correct, " +
"groupId={}, topicId={}, queueId={}, batchSize={}, offset={}->{}",
groupId, topicId, queueId, batchSize, offset, result.getNextBeginOffset());
return brokerController.getMessageStore().getMessageAsync(
groupId, topicId, queueId, result.getNextBeginOffset(), batchSize, filter);
}
return CompletableFuture.completedFuture(result);
}).whenComplete((result, throwable) -> {
if (throwable != null) {
log.error("Pop getMessageAsync error", throwable);
}
});
}
/**
* Fifo message does not have retry feature in broker
*/
public void setFifoBlocked(PopConsumerContext context,
String groupId, String topicId, int queueId, List<Long> queueOffsetList) {
brokerController.getConsumerOrderInfoManager().update(
context.getAttemptId(), false, topicId, groupId, queueId,
context.getPopTime(), context.getInvisibleTime(), queueOffsetList, context.getOrderCountInfoBuilder());
}
public boolean isFifoBlocked(PopConsumerContext context, String groupId, String topicId, int queueId) {
return brokerController.getConsumerOrderInfoManager().checkBlock(
context.getAttemptId(), topicId, groupId, queueId, context.getInvisibleTime());
}
protected CompletableFuture<PopConsumerContext> getMessageAsync(CompletableFuture<PopConsumerContext> future,
String clientHost, String groupId, String topicId, int queueId, int batchSize, MessageFilter filter,
PopConsumerRecord.RetryType retryType) {
return future.thenCompose(result -> {
// pop request too much, should not add rest count here
if (isPopShouldStop(groupId, topicId, queueId)) {
return CompletableFuture.completedFuture(result);
}
// Current requests would calculate the total number of messages
// waiting to be filtered for new message arrival notifications in
// the long-polling service, need disregarding the backlog in order
// consumption scenario. If rest message num including the blocked
// queue accumulation would lead to frequent unnecessary wake-ups
// of long-polling requests, resulting unnecessary CPU usage.
// When client ack message, long-polling request would be notifications
// by AckMessageProcessor.ackOrderly() and message will not be delayed.
if (result.isFifo() && isFifoBlocked(result, groupId, topicId, queueId)) {
// should not add accumulation(max offset - consumer offset) here
return CompletableFuture.completedFuture(result);
}
int remain = batchSize - result.getMessageCount();
if (remain <= 0) {
result.addRestCount(this.getPendingFilterCount(groupId, topicId, queueId));
return CompletableFuture.completedFuture(result);
} else {
final long consumeOffset = this.getPopOffset(groupId, topicId, queueId, result.getInitMode(), result.isFifo());
return getMessageAsync(clientHost, groupId, topicId, queueId, consumeOffset, remain, filter)
.thenApply(getMessageResult -> handleGetMessageResult(
result, getMessageResult, topicId, queueId, retryType, consumeOffset));
}
});
}
public CompletableFuture<PopConsumerContext> popAsync(String clientHost, long popTime, long invisibleTime,
String groupId, String topicId, int queueId, int batchSize, boolean fifo, String attemptId, int initMode,
MessageFilter filter) {
PopConsumerContext popConsumerContext =
new PopConsumerContext(clientHost, popTime, invisibleTime, groupId, fifo, initMode, attemptId);
TopicConfig topicConfig = brokerController.getTopicConfigManager().selectTopicConfig(topicId);
if (topicConfig == null || !consumerLockService.tryLock(groupId, topicId)) {
return CompletableFuture.completedFuture(popConsumerContext);
}
log.debug("PopConsumerService popAsync, groupId={}, topicId={}, queueId={}, " +
"batchSize={}, invisibleTime={}, fifo={}, attemptId={}, filter={}",
groupId, topicId, queueId, batchSize, invisibleTime, fifo, attemptId, filter);
String requestKey = groupId + "@" + topicId;
String retryTopicV1 = KeyBuilder.buildPopRetryTopicV1(topicId, groupId);
String retryTopicV2 = KeyBuilder.buildPopRetryTopicV2(topicId, groupId);
long requestCount = Objects.requireNonNull(ConcurrentHashMapUtils.computeIfAbsent(
requestCountTable, requestKey, k -> new AtomicLong(0L))).getAndIncrement();
boolean preferRetry = requestCount % 5L == 0L;
CompletableFuture<PopConsumerContext> getMessageFuture =
CompletableFuture.completedFuture(popConsumerContext);
try {
if (!fifo && preferRetry) {
if (brokerConfig.isRetrieveMessageFromPopRetryTopicV1()) {
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
retryTopicV1, 0, batchSize, filter, PopConsumerRecord.RetryType.RETRY_TOPIC_V1);
}
if (brokerConfig.isEnableRetryTopicV2()) {
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
retryTopicV2, 0, batchSize, filter, PopConsumerRecord.RetryType.RETRY_TOPIC_V2);
}
}
if (queueId != -1) {
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
topicId, queueId, batchSize, filter, PopConsumerRecord.RetryType.NORMAL_TOPIC);
} else {
for (int i = 0; i < topicConfig.getReadQueueNums(); i++) {
int current = (int) ((requestCount + i) % topicConfig.getReadQueueNums());
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
topicId, current, batchSize, filter, PopConsumerRecord.RetryType.NORMAL_TOPIC);
}
if (!fifo && !preferRetry) {
if (brokerConfig.isRetrieveMessageFromPopRetryTopicV1()) {
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
retryTopicV1, 0, batchSize, filter, PopConsumerRecord.RetryType.RETRY_TOPIC_V1);
}
if (brokerConfig.isEnableRetryTopicV2()) {
getMessageFuture = this.getMessageAsync(getMessageFuture, clientHost, groupId,
retryTopicV2, 0, batchSize, filter, PopConsumerRecord.RetryType.RETRY_TOPIC_V2);
}
}
}
return getMessageFuture.thenCompose(result -> {
if (result.isFound() && !result.isFifo()) {
if (brokerConfig.isEnablePopBufferMerge() &&
popConsumerCache != null && !popConsumerCache.isCacheFull()) {
this.popConsumerCache.writeRecords(result.getPopConsumerRecordList());
} else {
this.popConsumerStore.writeRecords(result.getPopConsumerRecordList());
}
for (int i = 0; i < result.getGetMessageResultList().size(); i++) {
GetMessageResult getMessageResult = result.getGetMessageResultList().get(i);
PopConsumerRecord popConsumerRecord = result.getPopConsumerRecordList().get(i);
// If the buffer belong retries message, the message needs to be re-encoded.
// The buffer should not be re-encoded when popResponseReturnActualRetryTopic
// is true or the current topic is not a retry topic.
boolean recode = brokerConfig.isPopResponseReturnActualRetryTopic();
if (recode && popConsumerRecord.isRetry()) {
result.getGetMessageResultList().set(i, this.recodeRetryMessage(
getMessageResult, popConsumerRecord.getTopicId(),
popConsumerRecord.getQueueId(), result.getPopTime(), invisibleTime));
}
}
}
return CompletableFuture.completedFuture(result);
}).whenComplete((result, throwable) -> {
try {
if (throwable != null) {
log.error("PopConsumerService popAsync get message error",
throwable instanceof CompletionException ? throwable.getCause() : throwable);
}
if (result.getMessageCount() > 0) {
log.debug("PopConsumerService popAsync result, found={}, groupId={}, topicId={}, queueId={}, " +
"batchSize={}, invisibleTime={}, fifo={}, attemptId={}, filter={}", result.getMessageCount(),
groupId, topicId, queueId, batchSize, invisibleTime, fifo, attemptId, filter);
}
} finally {
consumerLockService.unlock(groupId, topicId);
}
});
} catch (Throwable t) {
log.error("PopConsumerService popAsync error", t);
}
return getMessageFuture;
}
// Notify polling request when receive orderly ack
public CompletableFuture<Boolean> ackAsync(
long popTime, long invisibleTime, String groupId, String topicId, int queueId, long offset) {
if (brokerConfig.isPopConsumerKVServiceLog()) {
log.info("PopConsumerService ack, time={}, invisible={}, groupId={}, topic={}, queueId={}, offset={}",
popTime, invisibleTime, groupId, topicId, queueId, offset);
}
PopConsumerRecord record = new PopConsumerRecord(
popTime, groupId, topicId, queueId, 0, invisibleTime, offset, null);
if (brokerConfig.isEnablePopBufferMerge() && popConsumerCache != null) {
if (popConsumerCache.deleteRecords(Collections.singletonList(record)).isEmpty()) {
return CompletableFuture.completedFuture(true);
}
}
this.popConsumerStore.deleteRecords(Collections.singletonList(record));
return CompletableFuture.completedFuture(true);
}
// refer ChangeInvisibleTimeProcessor.appendCheckPointThenAckOrigin
public void changeInvisibilityDuration(long popTime, long invisibleTime,
long changedPopTime, long changedInvisibleTime, String groupId, String topicId, int queueId, long offset) {
if (brokerConfig.isPopConsumerKVServiceLog()) {
log.info("PopConsumerService change, time={}, invisible={}, " +
"groupId={}, topic={}, queueId={}, offset={}, new time={}, new invisible={}",
popTime, invisibleTime, groupId, topicId, queueId, offset, changedPopTime, changedInvisibleTime);
}
PopConsumerRecord ckRecord = new PopConsumerRecord(
changedPopTime, groupId, topicId, queueId, 0, changedInvisibleTime, offset, null);
PopConsumerRecord ackRecord = new PopConsumerRecord(
popTime, groupId, topicId, queueId, 0, invisibleTime, offset, null);
this.popConsumerStore.writeRecords(Collections.singletonList(ckRecord));
if (brokerConfig.isEnablePopBufferMerge() && popConsumerCache != null) {
if (popConsumerCache.deleteRecords(Collections.singletonList(ackRecord)).isEmpty()) {
return;
}
}
this.popConsumerStore.deleteRecords(Collections.singletonList(ackRecord));
}
// Use broker escape bridge to support remote read
public CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageAsync(PopConsumerRecord consumerRecord) {
return this.brokerController.getEscapeBridge().getMessageAsync(consumerRecord.getTopicId(),
consumerRecord.getOffset(), consumerRecord.getQueueId(), brokerConfig.getBrokerName(), false);
}
public CompletableFuture<Boolean> revive(PopConsumerRecord record) {
return this.getMessageAsync(record)
.thenCompose(result -> {
if (result == null) {
log.error("PopConsumerService revive error, message may be lost, record={}", record);
return CompletableFuture.completedFuture(false);
}
// true in triple right means get message needs to be retried
if (result.getLeft() == null) {
log.info("PopConsumerService revive no need retry, record={}", record);
return CompletableFuture.completedFuture(!result.getRight());
}
return CompletableFuture.completedFuture(this.reviveRetry(record, result.getLeft()));
});
}
public void clearCache(String groupId, String topicId, int queueId) {
while (consumerLockService.tryLock(groupId, topicId)) {
}
try {
if (popConsumerCache != null) {
popConsumerCache.removeRecords(groupId, topicId, queueId);
}
} finally {
consumerLockService.unlock(groupId, topicId);
}
}
public long revive(AtomicLong currentTime, int maxCount) {
Stopwatch stopwatch = Stopwatch.createStarted();
long upperTime = System.currentTimeMillis() - 50L;
List<PopConsumerRecord> consumerRecords = this.popConsumerStore.scanExpiredRecords(
currentTime.get() - TimeUnit.SECONDS.toMillis(3), upperTime, maxCount);
long scanCostTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
Queue<PopConsumerRecord> failureList = new LinkedBlockingQueue<>();
List<CompletableFuture<?>> futureList = new ArrayList<>(consumerRecords.size());
// could merge read operation here
for (PopConsumerRecord record : consumerRecords) {
futureList.add(this.revive(record).thenAccept(result -> {
if (!result) {
if (record.getAttemptTimes() < brokerConfig.getPopReviveMaxAttemptTimes()) {
long backoffInterval = 1000L * REWRITE_INTERVALS_IN_SECONDS[
Math.min(REWRITE_INTERVALS_IN_SECONDS.length, record.getAttemptTimes())];
long nextInvisibleTime = record.getInvisibleTime() + backoffInterval;
PopConsumerRecord retryRecord = new PopConsumerRecord(System.currentTimeMillis(),
record.getGroupId(), record.getTopicId(), record.getQueueId(),
record.getRetryFlag(), nextInvisibleTime, record.getOffset(), record.getAttemptId());
retryRecord.setAttemptTimes(record.getAttemptTimes() + 1);
failureList.add(retryRecord);
log.warn("PopConsumerService revive backoff retry, record={}", retryRecord);
} else {
log.error("PopConsumerService drop record, message may be lost, record={}", record);
}
}
}));
}
CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
this.popConsumerStore.writeRecords(new ArrayList<>(failureList));
this.popConsumerStore.deleteRecords(consumerRecords);
currentTime.set(consumerRecords.isEmpty() ?
upperTime : consumerRecords.get(consumerRecords.size() - 1).getVisibilityTimeout());
if (brokerConfig.isEnablePopBufferMerge()) {
log.info("PopConsumerService, key size={}, cache size={}, revive count={}, failure count={}, " +
"behindInMillis={}, scanInMillis={}, costInMillis={}",
popConsumerCache.getCacheKeySize(), popConsumerCache.getCacheSize(),
consumerRecords.size(), failureList.size(), upperTime - currentTime.get(),
scanCostTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));
} else {
log.info("PopConsumerService, revive count={}, failure count={}, " +
"behindInMillis={}, scanInMillis={}, costInMillis={}",
consumerRecords.size(), failureList.size(), upperTime - currentTime.get(),
scanCostTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
return consumerRecords.size();
}
public void createRetryTopicIfNeeded(String groupId, String topicId) {
TopicConfig topicConfig = brokerController.getTopicConfigManager().selectTopicConfig(topicId);
if (topicConfig != null) {
return;
}
topicConfig = new TopicConfig(topicId, 1, 1,
PermName.PERM_READ | PermName.PERM_WRITE, 0);
topicConfig.setTopicFilterType(TopicFilterType.SINGLE_TAG);
brokerController.getTopicConfigManager().updateTopicConfig(topicConfig);
long offset = this.brokerController.getConsumerOffsetManager().queryOffset(groupId, topicId, 0);
if (offset < 0) {
this.brokerController.getConsumerOffsetManager().commitOffset(
"InitPopOffset", groupId, topicId, 0, 0);
}
}
@SuppressWarnings("DuplicatedCode")
// org.apache.rocketmq.broker.processor.PopReviveService#reviveRetry
public boolean reviveRetry(PopConsumerRecord record, MessageExt messageExt) {
if (brokerConfig.isPopConsumerKVServiceLog()) {
log.info("PopConsumerService revive, time={}, invisible={}, groupId={}, topic={}, queueId={}, offset={}",
record.getPopTime(), record.getInvisibleTime(), record.getGroupId(), record.getTopicId(),
record.getQueueId(), record.getOffset());
}
boolean retry = StringUtils.startsWith(record.getTopicId(), MixAll.RETRY_GROUP_TOPIC_PREFIX);
String retryTopic = retry ? record.getTopicId() : KeyBuilder.buildPopRetryTopic(
record.getTopicId(), record.getGroupId(), brokerConfig.isEnableRetryTopicV2());
this.createRetryTopicIfNeeded(record.getGroupId(), retryTopic);
// deep copy here
MessageExtBrokerInner msgInner = new MessageExtBrokerInner();
msgInner.setTopic(retryTopic);
msgInner.setBody(messageExt.getBody() != null ? messageExt.getBody() : new byte[] {});
msgInner.setQueueId(0);
if (messageExt.getTags() != null) {
msgInner.setTags(messageExt.getTags());
} else {
MessageAccessor.setProperties(msgInner, new HashMap<>());
}
msgInner.setBornTimestamp(messageExt.getBornTimestamp());
msgInner.setFlag(messageExt.getFlag());
msgInner.setSysFlag(messageExt.getSysFlag());
msgInner.setBornHost(brokerController.getStoreHost());
msgInner.setStoreHost(brokerController.getStoreHost());
msgInner.setReconsumeTimes(messageExt.getReconsumeTimes() + 1);
msgInner.getProperties().putAll(messageExt.getProperties());
// set first pop time here
if (messageExt.getReconsumeTimes() == 0 ||
msgInner.getProperties().get(MessageConst.PROPERTY_FIRST_POP_TIME) == null) {
msgInner.getProperties().put(MessageConst.PROPERTY_FIRST_POP_TIME, String.valueOf(record.getPopTime()));
}
msgInner.setPropertiesString(MessageDecoder.messageProperties2String(msgInner.getProperties()));
PutMessageResult putMessageResult =
brokerController.getEscapeBridge().putMessageToSpecificQueue(msgInner);
if (putMessageResult.getAppendMessageResult() == null ||
putMessageResult.getAppendMessageResult().getStatus() != AppendMessageStatus.PUT_OK) {
log.error("PopConsumerService revive retry msg error, put status={}, ck={}, delay={}ms",
putMessageResult, JSON.toJSONString(record), System.currentTimeMillis() - record.getVisibilityTimeout());
return false;
}
if (this.brokerController.getBrokerStatsManager() != null) {
this.brokerController.getBrokerStatsManager().incBrokerPutNums(msgInner.getTopic(), 1);
this.brokerController.getBrokerStatsManager().incTopicPutNums(msgInner.getTopic());
this.brokerController.getBrokerStatsManager().incTopicPutSize(
msgInner.getTopic(), putMessageResult.getAppendMessageResult().getWroteBytes());
}
return true;
}
// Export kv store record to revive topic
@SuppressWarnings("ExtractMethodRecommender")
public synchronized void transferToFsStore() {
Stopwatch stopwatch = Stopwatch.createStarted();
while (true) {
try {
List<PopConsumerRecord> consumerRecords = this.popConsumerStore.scanExpiredRecords(
0, Long.MAX_VALUE, brokerConfig.getPopReviveMaxReturnSizePerRead());
if (consumerRecords == null || consumerRecords.isEmpty()) {
break;
}
for (PopConsumerRecord record : consumerRecords) {
PopCheckPoint ck = new PopCheckPoint();
ck.setBitMap(0);
ck.setNum((byte) 1);
ck.setPopTime(record.getPopTime());
ck.setInvisibleTime(record.getInvisibleTime());
ck.setStartOffset(record.getOffset());
ck.setCId(record.getGroupId());
ck.setTopic(record.getTopicId());
ck.setQueueId(record.getQueueId());
ck.setBrokerName(brokerConfig.getBrokerName());
ck.addDiff(0);
ck.setRePutTimes(ck.getRePutTimes());
int reviveQueueId = (int) record.getOffset() % brokerConfig.getReviveQueueNum();
MessageExtBrokerInner ckMsg =
brokerController.getPopMessageProcessor().buildCkMsg(ck, reviveQueueId);
brokerController.getMessageStore().asyncPutMessage(ckMsg).join();
}
log.info("PopConsumerStore transfer from kvStore to fsStore, count={}", consumerRecords.size());
this.popConsumerStore.deleteRecords(consumerRecords);
this.waitForRunning(1);
} catch (Throwable t) {
log.error("PopConsumerStore transfer from kvStore to fsStore failure", t);
}
}
log.info("PopConsumerStore transfer to fsStore finish, cost={}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
@Override
public String getServiceName() {
return PopConsumerService.class.getSimpleName();
}
@VisibleForTesting
protected PopConsumerKVStore getPopConsumerStore() {
return popConsumerStore;
}
public PopConsumerLockService getConsumerLockService() {
return consumerLockService;
}
@Override
public void start() {
if (!this.popConsumerStore.start()) {
throw new RuntimeException("PopConsumerStore init error");
}
if (this.popConsumerCache != null) {
this.popConsumerCache.start();
}
super.start();
}
@Override
public void shutdown() {
// Block shutdown thread until write records finish
super.shutdown();
do {
this.waitForRunning(10);
}
while (consumerRunning.get());
if (this.popConsumerCache != null) {
this.popConsumerCache.shutdown();
}
if (this.popConsumerStore != null) {
this.popConsumerStore.shutdown();
}
}
@Override
public void run() {
this.consumerRunning.set(true);
while (!isStopped()) {
try {
// to prevent concurrency issues during read and write operations
long reviveCount = this.revive(this.currentTime,
brokerConfig.getPopReviveMaxReturnSizePerRead());
long current = System.currentTimeMillis();
if (lastCleanupLockTime.get() + TimeUnit.MINUTES.toMillis(1) < current) {
this.consumerLockService.removeTimeout();
this.lastCleanupLockTime.set(current);
}
if (reviveCount < brokerConfig.getPopReviveMaxReturnSizePerRead()) {
this.waitForRunning(500);
}
} catch (Exception e) {
log.error("PopConsumerService revive error", e);
this.waitForRunning(500);
}
}
this.consumerRunning.set(false);
}
}
|
apache/xmlbeans | 38,247 | src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java | /* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.impl.schema;
import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.IOUtil;
import org.apache.xmlbeans.impl.common.XmlEncodingSniffer;
import org.apache.xmlbeans.impl.xb.xsdschema.ImportDocument.Import;
import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument.Include;
import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;
public class StscImporter {
public static SchemaToProcess[] resolveImportsAndIncludes(Schema[] startWith, boolean forceSrcSave) {
DownloadTable engine = new DownloadTable(startWith);
return engine.resolveImportsAndIncludes(forceSrcSave);
}
public static class SchemaToProcess {
private final Schema schema;
private final String chameleonNamespace;
// list of SchemaToProcess objects directly included by this
private List<SchemaToProcess> includes;
// list of SchemaToProcess objects directly redefined by this
private List<SchemaToProcess> redefines;
// list of Redefine objects associated to each redefinition
private List<Redefine> redefineObjects;
// set of SchemaToProcess objects directly/indirectly included by this
private Set<SchemaToProcess> indirectIncludes;
// set of SchemaToProcess objects that include this directly/indirectly
private Set<SchemaToProcess> indirectIncludedBy;
public SchemaToProcess(Schema schema, String chameleonNamespace) {
this.schema = schema;
this.chameleonNamespace = chameleonNamespace;
}
/**
* The schema to parse.
*/
public Schema getSchema() {
return schema;
}
/**
* The base URI for this stp
*/
public String getSourceName() {
return schema.documentProperties().getSourceName();
}
/**
* The chameleon namespace. Null if this schema is not being treated
* as a chameleon. (The ordinary targetNamespace will just be extracted
* from the syntax of the schema.)
*/
public String getChameleonNamespace() {
return chameleonNamespace;
}
/**
* This method and the remaining methods are used to represent a
* directed graph of includes/redefines. This is required in order
* to establish identity component by component, as required in
* xmlschema-1, chapter 4.2.2
*/
public List<SchemaToProcess> getRedefines() {
return redefines;
}
public List<Redefine> getRedefineObjects() {
return redefineObjects;
}
private void addInclude(SchemaToProcess include) {
if (includes == null) {
includes = new ArrayList<>();
}
includes.add(include);
}
private void addRedefine(SchemaToProcess redefine, Redefine object) {
if (redefines == null || redefineObjects == null) {
redefines = new ArrayList<>();
redefineObjects = new ArrayList<>();
}
redefines.add(redefine);
redefineObjects.add(object);
}
private void buildIndirectReferences() {
if (includes != null) {
for (SchemaToProcess schemaToProcess : includes) {
/* We have a this-schemaToProcess vertex
* This means that all nodes accessible from schemaToProcess are
* also accessible from this and all nodes that have access to
* this also have access to schemaToProcess */
this.addIndirectIncludes(schemaToProcess);
}
}
// Repeat the same algorithm for redefines, since redefines are also includes
if (redefines != null) {
for (SchemaToProcess schemaToProcess : redefines) {
this.addIndirectIncludes(schemaToProcess);
}
}
}
private void addIndirectIncludes(SchemaToProcess schemaToProcess) {
if (indirectIncludes == null) {
indirectIncludes = new HashSet<>();
}
indirectIncludes.add(schemaToProcess);
if (schemaToProcess.indirectIncludedBy == null) {
schemaToProcess.indirectIncludedBy = new HashSet<>();
}
schemaToProcess.indirectIncludedBy.add(this);
addIndirectIncludesHelper(this, schemaToProcess);
if (indirectIncludedBy != null) {
for (SchemaToProcess stp : indirectIncludedBy) {
stp.indirectIncludes.add(schemaToProcess);
schemaToProcess.indirectIncludedBy.add(stp);
addIndirectIncludesHelper(stp, schemaToProcess);
}
}
}
private static void addIndirectIncludesHelper(SchemaToProcess including,
SchemaToProcess schemaToProcess) {
if (schemaToProcess.indirectIncludes != null) {
for (SchemaToProcess stp : schemaToProcess.indirectIncludes) {
including.indirectIncludes.add(stp);
stp.indirectIncludedBy.add(including);
}
}
}
public boolean indirectIncludes(SchemaToProcess schemaToProcess) {
return indirectIncludes != null && indirectIncludes.contains(schemaToProcess);
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SchemaToProcess)) {
return false;
}
final SchemaToProcess schemaToProcess = (SchemaToProcess) o;
if (!Objects.equals(chameleonNamespace, schemaToProcess.chameleonNamespace)) {
return false;
}
return schema == schemaToProcess.schema;
}
public int hashCode() {
int result;
result = schema.hashCode();
result = 29 * result + (chameleonNamespace != null ? chameleonNamespace.hashCode() : 0);
return result;
}
}
private final static String PROJECT_URL_PREFIX = "project://local";
private static String baseURLForDoc(XmlObject obj) {
String path = obj.documentProperties().getSourceName();
if (path == null) {
return null;
}
if (path.startsWith("/")) {
return PROJECT_URL_PREFIX + path.replace('\\', '/');
}
// looks like a URL?
int colon = path.indexOf(':');
if (colon > 1 && path.substring(0, colon).matches("^\\w+$")) {
return path;
}
return PROJECT_URL_PREFIX + "/" + path.replace('\\', '/');
}
private static URI parseURI(String s) {
if (s == null) {
return null;
}
try {
return new URI(s);
} catch (URISyntaxException syntax) {
return null;
}
}
//workaround for Sun bug # 4723726
public static URI resolve(URI base, String child)
throws URISyntaxException {
URI childUri = new URI(child);
URI ruri = base.resolve(childUri);
// if the child fragment is relative (which we'll assume is the case
// if URI.resolve doesn't do anything useful with it) and the base
// URI is pointing at something nested inside a jar, we seem to have
// to this ourselves to make sure that the nested jar url gets
// resolved correctly
if (childUri.equals(ruri) && !childUri.isAbsolute() &&
(base.getScheme().equals("jar") || base.getScheme().equals("zip"))) {
String r = base.toString();
int lastslash = r.lastIndexOf('/');
r = r.substring(0, lastslash) + "/" + childUri;
// Sun's implementation of URI doesn't support references to the
// parent directory ("/..") in the part after "!/" so we have to
// remove these ourselves
int exclPointSlashIndex = r.lastIndexOf("!/");
if (exclPointSlashIndex > 0) {
int slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex);
while (slashDotDotIndex > 0) {
int prevSlashIndex = r.lastIndexOf("/", slashDotDotIndex - 1);
if (prevSlashIndex >= exclPointSlashIndex) {
String temp = r.substring(slashDotDotIndex + 3);
r = r.substring(0, prevSlashIndex).concat(temp);
}
slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex);
}
}
return URI.create(r);
}
//fix up normalization bug
if ("file".equals(ruri.getScheme()) && !child.equals(ruri.getPath())) {
if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) {
String path = "///".concat(ruri.getPath());
try {
ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment());
} catch (URISyntaxException ignored) {
}
}
}
return ruri;
}
public static class DownloadTable {
/**
* Namespace/schemaLocation pair.
* <p>
* Downloaded schemas are indexed by namespace, schemaLocation, and both.
* <p>
* A perfect match is preferred, but a match-by-namespace is accepted.
* A match-by-schemaLocation is only accepted for includes (not imports).
*/
private static class NsLocPair {
private final String namespaceURI;
private final String locationURL;
public NsLocPair(String namespaceURI, String locationURL) {
this.namespaceURI = namespaceURI;
this.locationURL = locationURL;
}
/**
* Empty string for no-namespace, null for namespace-not-part-of-key
*/
public String getNamespaceURI() {
return namespaceURI;
}
public String getLocationURL() {
return locationURL;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof NsLocPair)) {
return false;
}
final NsLocPair nsLocPair = (NsLocPair) o;
if (!Objects.equals(locationURL, nsLocPair.locationURL)) {
return false;
}
return Objects.equals(namespaceURI, nsLocPair.namespaceURI);
}
public int hashCode() {
int result;
result = (namespaceURI != null ? namespaceURI.hashCode() : 0);
result = 29 * result + (locationURL != null ? locationURL.hashCode() : 0);
return result;
}
}
private static class DigestKey {
byte[] _digest;
int _hashCode;
DigestKey(byte[] digest) {
_digest = digest;
for (int i = 0; i < 4 && i < digest.length; i++) {
_hashCode = _hashCode << 8;
_hashCode = _hashCode + digest[i];
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DigestKey)) {
return false;
}
return Arrays.equals(_digest, ((DigestKey) o)._digest);
}
public int hashCode() {
return _hashCode;
}
}
private final Map<NsLocPair, Schema> schemaByNsLocPair = new HashMap<>();
private final Map<DigestKey, Schema> schemaByDigestKey = new HashMap<>();
private final LinkedList<SchemaToProcess> scanNeeded = new LinkedList<>();
private final Set<Schema> emptyNamespaceSchemas = new HashSet<>();
private final Map<SchemaToProcess, SchemaToProcess> scannedAlready = new HashMap<>();
private final Set<String> failedDownloads = new HashSet<>();
private Schema downloadSchema(XmlObject referencedBy, String targetNamespace, String locationURL) {
// no location URL provided? Then nothing to do.
if (locationURL == null) {
return null;
}
StscState state = StscState.get();
// First resolve relative URLs with respect to base URL for doc
URI baseURI = parseURI(baseURLForDoc(referencedBy));
final String absoluteURL;
try {
absoluteURL = baseURI == null ? locationURL : resolve(baseURI, locationURL).toString();
} catch (URISyntaxException e) {
state.error("Could not find resource - invalid location URL: " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
return null;
}
assert (absoluteURL != null);
// probe 0: this url is already processed, from a previous compile
if (state.isFileProcessed(absoluteURL)) {
return null;
}
// probe 1: ns+url - perfect match
if (targetNamespace != null) {
Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, absoluteURL));
if (result != null) {
return result;
}
}
// probe 2: we have preexisting knowledge of this namespace,
// either from another schema file or from the linker.
// If we're not downloading the given URL, skip it silently if the
// namespace is already represented by a file we have.
// Also, suppress downloads of URLs to namespaces that are already
// known by the linker.
// (We never assume preexisting knowledge of the no-namespace,
// even if we have some definitions, since it's likely that
// more than one person is playing in the no-namespace at once.)
if (targetNamespace != null && !targetNamespace.equals("")) {
// the URL is not one to download; should we assume we know about the namespace?
if (!state.shouldDownloadURI(absoluteURL)) {
// If we already have a schema representing this namespace,
// then skip this URL silently without producing an error.
Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, null));
if (result != null) {
return result;
}
}
// If the linker already knows about this namespace, skip
// this URL.
if (state.linkerDefinesNamespace(targetNamespace)) {
return null;
}
}
// probe 3: url only
final Schema result2 = schemaByNsLocPair.get(new NsLocPair(null, absoluteURL));
if (result2 != null) {
return result2;
}
// no match: error if we can't or won't download.
if (previouslyFailedToDownload(absoluteURL)) {
// an error message has already been produced.
return null;
}
if (!state.shouldDownloadURI(absoluteURL)) {
state.error("Could not load resource \"" + absoluteURL + "\" (network downloads disabled).", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
addFailedDownload(absoluteURL);
return null;
}
// try to download
download:
try {
XmlObject xdoc = downloadDocument(state.getS4SLoader(), targetNamespace, absoluteURL);
Schema result = findMatchByDigest(xdoc);
String shortname = state.relativize(absoluteURL);
if (result != null) {
// if an exactly-the-same document has already been loaded, use the original and spew
String dupname = state.relativize(result.documentProperties().getSourceName());
if (dupname != null) {
state.info(shortname + " is the same as " + dupname + " (ignoring the duplicate file)");
} else {
state.info(shortname + " is the same as another schema");
}
} else {
// otherwise, it's a new document: validate it and grab the contents
XmlOptions voptions = new XmlOptions();
voptions.setErrorListener(state.getErrorListener());
if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) {
state.error("Referenced document is not a valid schema", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
break download;
}
SchemaDocument sDoc = (SchemaDocument) xdoc;
result = sDoc.getSchema();
state.info("Loading referenced file " + shortname);
}
NsLocPair key = new NsLocPair(emptyStringIfNull(result.getTargetNamespace()), absoluteURL);
addSuccessfulDownload(key, result);
return result;
} catch (MalformedURLException malformed) {
state.error("URL \"" + absoluteURL + "\" is not well-formed", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
} catch (IOException connectionProblem) {
state.error(connectionProblem.toString(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
} catch (XmlException e) {
state.error("Problem parsing referenced XML resource - " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
}
// record failure so that we don't try to download this URL again
addFailedDownload(absoluteURL);
return null;
}
static XmlObject downloadDocument(SchemaTypeLoader loader, String namespace, String absoluteURL)
throws IOException, XmlException {
StscState state = StscState.get();
EntityResolver resolver = state.getEntityResolver();
if (resolver != null) {
InputSource source;
try {
source = resolver.resolveEntity(namespace, absoluteURL);
} catch (SAXException e) {
throw new XmlException(e);
}
if (source != null) {
state.addSourceUri(absoluteURL, null);
// first preference for InputSource contract: character stream
Reader reader = source.getCharacterStream();
if (reader != null) {
reader = copySchemaSource(absoluteURL, reader, state);
XmlOptions options = new XmlOptions();
options.setLoadLineNumbers();
options.setDocumentSourceName(absoluteURL);
return loader.parse(reader, null, options);
}
// second preference for InputSource contract:
InputStream bytes = source.getByteStream();
if (bytes != null) {
bytes = copySchemaSource(absoluteURL, bytes, state);
String encoding = source.getEncoding();
XmlOptions options = new XmlOptions();
options.setLoadLineNumbers();
options.setLoadMessageDigest();
options.setDocumentSourceName(absoluteURL);
if (encoding != null) {
options.setCharacterEncoding(encoding);
}
return loader.parse(bytes, null, options);
}
// third preference: use the (possibly redirected) url
String urlToLoad = source.getSystemId();
if (urlToLoad == null) {
throw new IOException("EntityResolver unable to resolve " + absoluteURL + " (for namespace " + namespace + ")");
}
copySchemaSource(absoluteURL, state, false);
XmlOptions options = new XmlOptions();
options.setLoadLineNumbers();
options.setLoadMessageDigest();
options.setDocumentSourceName(absoluteURL);
URL urlDownload = new URL(urlToLoad);
return loader.parse(urlDownload, null, options);
}
}
// no resolver - just use the URL directly, no substitution
state.addSourceUri(absoluteURL, null);
copySchemaSource(absoluteURL, state, false);
XmlOptions options = new XmlOptions();
options.setLoadLineNumbers();
options.setLoadMessageDigest();
URL urlDownload = new URL(absoluteURL);
return loader.parse(urlDownload, null, options);
}
private void addSuccessfulDownload(NsLocPair key, Schema schema) {
byte[] digest = schema.documentProperties().getMessageDigest();
if (digest == null) {
StscState.get().addSchemaDigest(null);
} else {
DigestKey dk = new DigestKey(digest);
if (!schemaByDigestKey.containsKey(dk)) {
schemaByDigestKey.put(new DigestKey(digest), schema);
StscState.get().addSchemaDigest(digest);
}
}
schemaByNsLocPair.put(key, schema);
NsLocPair key1 = new NsLocPair(key.getNamespaceURI(), null);
if (!schemaByNsLocPair.containsKey(key1)) {
schemaByNsLocPair.put(key1, schema);
}
NsLocPair key2 = new NsLocPair(null, key.getLocationURL());
if (!schemaByNsLocPair.containsKey(key2)) {
schemaByNsLocPair.put(key2, schema);
}
}
private Schema findMatchByDigest(XmlObject original) {
byte[] digest = original.documentProperties().getMessageDigest();
if (digest == null) {
return null;
}
return schemaByDigestKey.get(new DigestKey(digest));
}
private void addFailedDownload(String locationURL) {
failedDownloads.add(locationURL);
}
private boolean previouslyFailedToDownload(String locationURL) {
return failedDownloads.contains(locationURL);
}
private static boolean nullableStringsMatch(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return (s1.equals(s2));
}
private static String emptyStringIfNull(String s) {
if (s == null) {
return "";
}
return s;
}
private SchemaToProcess addScanNeeded(SchemaToProcess stp) {
if (!scannedAlready.containsKey(stp)) {
scannedAlready.put(stp, stp);
scanNeeded.add(stp);
return stp;
} else {
return scannedAlready.get(stp);
}
}
private void addEmptyNamespaceSchema(Schema s) {
emptyNamespaceSchemas.add(s);
}
private void usedEmptyNamespaceSchema(Schema s) {
emptyNamespaceSchemas.remove(s);
}
private boolean fetchRemainingEmptyNamespaceSchemas() {
if (emptyNamespaceSchemas.isEmpty()) {
return false;
}
for (Schema schema : emptyNamespaceSchemas) {
addScanNeeded(new SchemaToProcess(schema, null));
}
emptyNamespaceSchemas.clear();
return true;
}
private boolean hasNextToScan() {
return !scanNeeded.isEmpty();
}
private SchemaToProcess nextToScan() {
return scanNeeded.removeFirst();
}
public DownloadTable(Schema[] startWith) {
for (Schema schema : startWith) {
String targetNamespace = schema.getTargetNamespace();
NsLocPair key = new NsLocPair(targetNamespace, baseURLForDoc(schema));
addSuccessfulDownload(key, schema);
if (targetNamespace != null) {
addScanNeeded(new SchemaToProcess(schema, null));
} else {
addEmptyNamespaceSchema(schema);
}
}
}
public SchemaToProcess[] resolveImportsAndIncludes(boolean forceSave) {
StscState state = StscState.get();
List<SchemaToProcess> result = new ArrayList<>();
boolean hasRedefinitions = false;
// algorithm is to scan through each schema document and
// 1. download each import and include (if not already downloaded)
// 2. queue each imported or included schema to be process (if not already queued)
// The algorithm is run twice: first we begin with non-empty
// namespace schemas only. Then we repeat starting with any
// empty empty-namespace schemas that have NOT been chameleon-
// included by other schemas and process them.
do {
while (hasNextToScan()) {
SchemaToProcess stp = nextToScan();
String uri = stp.getSourceName();
state.addSourceUri(uri, null);
result.add(stp);
copySchemaSource(uri, state, forceSave);
{
// handle imports
Import[] imports = stp.getSchema().getImportArray();
for (Import anImport : imports) {
Schema imported = downloadSchema(anImport, emptyStringIfNull(anImport.getNamespace()), anImport.getSchemaLocation());
// if download fails, an error has already been reported.
if (imported == null) {
continue;
}
if (!nullableStringsMatch(imported.getTargetNamespace(), anImport.getNamespace())) {
StscState.get().error("Imported schema has a target namespace \"" + imported.getTargetNamespace() + "\" that does not match the specified \"" + anImport.getNamespace() + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, anImport);
} else {
addScanNeeded(new SchemaToProcess(imported, null));
}
}
}
{
// handle includes
Include[] includes = stp.getSchema().getIncludeArray();
String sourceNamespace = stp.getChameleonNamespace();
if (sourceNamespace == null) {
sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace());
}
for (Include include : includes) {
Schema included = downloadSchema(include, null, include.getSchemaLocation());
// if download fails, an error has already been reported.
if (included == null) {
continue;
}
if (emptyStringIfNull(included.getTargetNamespace()).equals(sourceNamespace)) {
// non-chameleon case - just like an import
SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, null));
stp.addInclude(s);
} else if (included.getTargetNamespace() != null) {
// illegal include: included schema in wrong namespace.
StscState.get().error("Included schema has a target namespace \"" + included.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, include);
} else {
// chameleon include
SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, sourceNamespace));
stp.addInclude(s);
usedEmptyNamespaceSchema(included);
}
}
}
{
// handle redefines
Redefine[] redefines = stp.getSchema().getRedefineArray();
String sourceNamespace = stp.getChameleonNamespace();
if (sourceNamespace == null) {
sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace());
}
for (Redefine redefine : redefines) {
Schema redefined = downloadSchema(redefine, null, redefine.getSchemaLocation());
// if download fails, an error has already been reported.
if (redefined == null) {
continue;
}
if (emptyStringIfNull(redefined.getTargetNamespace()).equals(sourceNamespace)) {
// non-chameleon case
SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, null));
stp.addRedefine(s, redefine);
hasRedefinitions = true;
} else if (redefined.getTargetNamespace() != null) {
// illegal include: included schema in wrong namespace.
StscState.get().error("Redefined schema has a target namespace \"" + redefined.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, redefine);
} else {
// chameleon redefine
SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, sourceNamespace));
stp.addRedefine(s, redefine);
usedEmptyNamespaceSchema(redefined);
hasRedefinitions = true;
}
}
}
}
} while (fetchRemainingEmptyNamespaceSchemas());
// Build the lists of indirect references
// Make all the effort only if there are redefinitions
if (hasRedefinitions) {
for (SchemaToProcess schemaToProcess : result) {
schemaToProcess.buildIndirectReferences();
}
}
return result.toArray(new SchemaToProcess[0]);
}
private static Reader copySchemaSource(String url, Reader reader, StscState state) {
//Copy the schema file if it wasn't already copied
if (state.getSchemasDir() == null) {
return reader;
}
String schemalocation = state.sourceNameForUri(url);
File targetFile = new File(state.getSchemasDir(), schemalocation);
if (targetFile.exists()) {
return reader;
}
try {
File parentDir = new File(targetFile.getParent());
IOUtil.createDir(parentDir, null);
CharArrayReader car = copy(reader);
XmlEncodingSniffer xes = new XmlEncodingSniffer(car, null);
try (Writer out = new OutputStreamWriter(
Files.newOutputStream(targetFile.toPath()), xes.getXmlEncoding())) {
IOUtil.copyCompletely(car, out);
}
car.reset();
return car;
} catch (IOException e) {
System.err.println("IO Error " + e);
return reader;
}
}
private static InputStream copySchemaSource(String url, InputStream bytes, StscState state) {
//Copy the schema file if it wasn't already copied
if (state.getSchemasDir() == null) {
return bytes;
}
String schemalocation = state.sourceNameForUri(url);
File targetFile = new File(state.getSchemasDir(), schemalocation);
if (targetFile.exists()) {
return bytes;
}
try {
File parentDir = new File(targetFile.getParent());
IOUtil.createDir(parentDir, null);
ByteArrayInputStream bais = copy(bytes);
try (OutputStream out = Files.newOutputStream(targetFile.toPath())) {
IOUtil.copyCompletely(bais, out);
}
bais.reset();
return bais;
} catch (IOException e) {
System.err.println("IO Error " + e);
return bytes;
}
}
private static void copySchemaSource(String urlLoc, StscState state, boolean forceCopy) {
//Copy the schema file if it wasn't already copied
if (state.getSchemasDir() != null) {
String schemalocation = state.sourceNameForUri(urlLoc);
File targetFile = new File(state.getSchemasDir(), schemalocation);
if (forceCopy || !targetFile.exists()) {
InputStream in = null;
try {
File parentDir = new File(targetFile.getParent());
IOUtil.createDir(parentDir, null);
URL url = new URL(urlLoc);
// Copy the file from filepath to schema[METADATA_PACKAGE_GEN]/src/<schemaFile>
try {
in = url.openStream();
} catch (FileNotFoundException fnfe) {
if (forceCopy && targetFile.exists()) {
targetFile.delete();
} else {
throw fnfe;
}
}
if (in != null) {
OutputStream out = Files.newOutputStream(targetFile.toPath());
IOUtil.copyCompletely(in, out);
}
} catch (IOException e) {
System.err.println("IO Error " + e);
// failure = true; - not cause for failure
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// ignore
}
}
}
}
}
}
private static ByteArrayInputStream copy(InputStream is) throws IOException {
byte[] buf = new byte[1024];
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int bytesRead;
while ((bytesRead = is.read(buf, 0, 1024)) > 0) {
baos.write(buf, 0, bytesRead);
}
return new ByteArrayInputStream(baos.toByteArray());
}
}
private static CharArrayReader copy(Reader is) throws IOException {
char[] buf = new char[1024];
try (CharArrayWriter charArrayWriter = new CharArrayWriter()) {
int charRead;
while ((charRead = is.read(buf, 0, 1024)) > 0) {
charArrayWriter.write(buf, 0, charRead);
}
return new CharArrayReader(charArrayWriter.toCharArray());
}
}
}
}
|
apache/tomcat80 | 37,748 | test/org/apache/coyote/ajp/TestAbstractAjpProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.coyote.ajp;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
public class TestAbstractAjpProcessor extends TomcatBaseTest {
@Override
protected String getProtocol() {
/*
* The tests are all setup for HTTP so need to convert the protocol
* values to AJP.
*/
// Has a protocol been specified
String protocol = System.getProperty("tomcat.test.protocol");
// Use BIO by default
if (protocol == null) {
protocol = "org.apache.coyote.ajp.AjpProtocol";
} else if (protocol.contains("Nio2")) {
protocol = "org.apache.coyote.ajp.AjpNio2Protocol";
} else if (protocol.contains("Nio")) {
protocol = "org.apache.coyote.ajp.AjpNioProtocol";
} else if (protocol.contains("Apr")) {
protocol = "org.apache.coyote.ajp.AjpAprProtocol";
} else {
protocol = "org.apache.coyote.ajp.AjpProtocol";
}
return protocol;
}
private void doSnoopTest(RequestDescriptor desc) throws Exception {
final int ajpPacketSize = 16000;
Map<String, String> requestInfo = desc.getRequestInfo();
Map<String, String> contextInitParameters = desc.getContextInitParameters();
Map<String, String> contextAttributes = desc.getContextAttributes();
Map<String, String> headers = desc.getHeaders();
Map<String, String> attributes = desc.getAttributes();
Map<String, String> params = desc.getParams();
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setProperty("packetSize", Integer.toString(ajpPacketSize));
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "snoop", new SnoopServlet());
ctx.addServletMappingDecoded("/", "snoop");
SimpleAjpClient ajpClient = new SimpleAjpClient(ajpPacketSize);
if (requestInfo.get("REQUEST-QUERY-STRING") != null &&
params.size() > 0) {
throw(new IllegalArgumentException("Request setting " +
"'REQUEST-QUERY-STRING' and explicit params not allowed " +
"together"));
}
String value;
int bodySize = 0;
Map<String, String> savedRequestInfo = new HashMap<>();
for (String name: requestInfo.keySet()) {
value = requestInfo.get(name);
switch (name) {
case "REQUEST-METHOD":
ajpClient.setMethod(value);
break;
case "REQUEST-PROTOCOL":
ajpClient.setProtocol(value);
break;
case "REQUEST-URI":
ajpClient.setUri(value);
break;
case "REQUEST-REMOTE-HOST":
/* request.getRemoteHost() will default to
* request.getRemoteAddr() unless enableLookups is set. */
tomcat.getConnector().setEnableLookups(true);
ajpClient.setRemoteHost(value);
break;
case "REQUEST-REMOTE-ADDR":
ajpClient.setRemoteAddr(value);
break;
case "REQUEST-SERVER-NAME":
ajpClient.setServerName(value);
break;
case "REQUEST-SERVER-PORT":
ajpClient.setServerPort(Integer.parseInt(value));
break;
case "REQUEST-IS-SECURE":
ajpClient.setSsl(Boolean.parseBoolean(value));
break;
case "REQUEST-LOCAL-ADDR":
savedRequestInfo.put(name, value);
break;
case "REQUEST-REMOTE-PORT":
savedRequestInfo.put(name, value);
break;
case "REQUEST-REMOTE-USER":
case "REQUEST-ROUTE":
case "REQUEST-SECRET":
case "REQUEST-AUTH-TYPE":
case "REQUEST-QUERY-STRING":
savedRequestInfo.put(name, value);
break;
case "REQUEST-CONTENT-LENGTH":
headers.put("CONTENT-LENGTH", value);
break;
case "REQUEST-BODY-SIZE":
savedRequestInfo.put(name, value);
bodySize = Integer.parseInt(value);
break;
case "REQUEST-CONTENT-TYPE":
headers.put("CONTENT-TYPE", value);
break;
/* Not yet implemented or not (easily) possible to implement */
case "REQUEST-LOCAL-NAME": //request.getLocalName()
case "REQUEST-LOCAL-PORT": //request.getLocalPort()
case "REQUEST-SCHEME": //request.getScheme()
case "REQUEST-URL": //request.getRequestURL()
case "REQUEST-CONTEXT-PATH": //request.getContextPath()
case "REQUEST-SERVLET-PATH": //request.getServletPath()
case "REQUEST-PATH-INFO": //request.getPathInfo()
case "REQUEST-PATH-TRANSLATED": //request.getPathTranslated()
case "REQUEST-USER-PRINCIPAL": //request.getUserPrincipal()
case "REQUEST-CHARACTER-ENCODING": //request.getCharacterEncoding()
case "REQUEST-LOCALE": //request.getLocale()
case "SESSION-REQUESTED-ID": //request.getRequestedSessionId()
case "SESSION-REQUESTED-ID-COOKIE": //request.isRequestedSessionIdFromCookie()
case "SESSION-REQUESTED-ID-URL": //request.isRequestedSessionIdFromUrl()
case "SESSION-REQUESTED-ID-VALID": //request.isRequestedSessionIdValid()
default:
throw(new IllegalArgumentException("Request setting '" + name + "' not supported"));
}
}
ServletContext sc = ctx.getServletContext();
for (String name: contextInitParameters.keySet()) {
sc.setInitParameter(name, contextInitParameters.get(name));
}
for (String name: contextAttributes.keySet()) {
sc.setAttribute(name, contextAttributes.get(name));
}
/* Basic request properties must be set before this call */
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
for (String name: savedRequestInfo.keySet()) {
value = savedRequestInfo.get(name);
switch (name) {
case "REQUEST-LOCAL-ADDR":
forwardMessage.addAttribute("AJP_LOCAL_ADDR", value);
break;
case "REQUEST-REMOTE-PORT":
forwardMessage.addAttribute("AJP_REMOTE_PORT", value);
break;
case "REQUEST-REMOTE-USER":
/* request.getRemoteUser() will not trust the AJP
* info if tomcatAuthentication is set. */
tomcat.getConnector().setProperty("tomcatAuthentication", "false");
forwardMessage.addAttribute(0x03, value);
break;
case "REQUEST-AUTH-TYPE":
/* request.getAuthType() will not trust the AJP
* info if tomcatAuthentication is set. */
tomcat.getConnector().setProperty("tomcatAuthentication", "false");
forwardMessage.addAttribute(0x04, value);
break;
case "REQUEST-QUERY-STRING":
forwardMessage.addAttribute(0x05, value);
break;
case "REQUEST-ROUTE":
forwardMessage.addAttribute(0x06, value);
break;
case "REQUEST-SECRET":
forwardMessage.addAttribute(0x0C, value);
break;
case "REQUEST-BODY-SIZE":
break;
default:
throw(new IllegalArgumentException("Request setting '" + name + "' not supported"));
}
}
if (params.size() > 0) {
StringBuilder query = new StringBuilder();
boolean sep = false;
for (String name: params.keySet()) {
if (sep) {
query.append("&");
} else {
sep = true;
}
query.append(name);
query.append("=");
query.append(params.get(name));
}
forwardMessage.addAttribute(0x05, query.toString());
}
for (String name: headers.keySet()) {
value = headers.get(name);
name = name.toUpperCase(Locale.ENGLISH);
switch (name) {
case "ACCEPT":
forwardMessage.addHeader(0xA001, value);
break;
case "ACCEPT-CHARSET":
forwardMessage.addHeader(0xA002, value);
break;
case "ACCEPT-ENCODING":
forwardMessage.addHeader(0xA003, value);
break;
case "ACCEPT-LANGUAGE":
forwardMessage.addHeader(0xA004, value);
break;
case "AUTHORIZATION":
forwardMessage.addHeader(0xA005, value);
break;
case "CONNECTION":
forwardMessage.addHeader(0xA006, value);
break;
case "CONTENT-TYPE":
forwardMessage.addHeader(0xA007, value);
break;
case "CONTENT-LENGTH":
forwardMessage.addHeader(0xA008, value);
break;
case "COOKIE":
forwardMessage.addHeader(0xA009, value);
break;
case "COOKIE2":
forwardMessage.addHeader(0xA00A, value);
break;
case "HOST":
forwardMessage.addHeader(0xA00B, value);
break;
case "PRAGMA":
forwardMessage.addHeader(0xA00C, value);
break;
case "REFERER":
forwardMessage.addHeader(0xA00D, value);
break;
case "USER-AGENT":
forwardMessage.addHeader(0xA00E, value);
break;
default:
forwardMessage.addHeader(name, value);
break;
}
}
for (String name: attributes.keySet()) {
value = attributes.get(name);
forwardMessage.addAttribute(name, value);
}
// Complete the message
forwardMessage.end();
tomcat.start();
ajpClient.setPort(getPort());
ajpClient.connect();
TesterAjpMessage responseHeaders = null;
if (bodySize == 0) {
responseHeaders = ajpClient.sendMessage(forwardMessage);
} else {
TesterAjpMessage bodyMessage = ajpClient.createBodyMessage(new byte[bodySize]);
responseHeaders = ajpClient.sendMessage(forwardMessage, bodyMessage);
// Expect back a request for more data (which will be empty and
// trigger end of stream in Servlet)
validateGetBody(responseHeaders);
bodyMessage = ajpClient.createBodyMessage(new byte[0]);
responseHeaders = ajpClient.sendMessage(bodyMessage);
}
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 200, "OK");
String body = extractResponseBody(ajpClient.readMessage());
RequestDescriptor result = SnoopResult.parse(body);
/* AJP attributes result in Coyote Request attributes, which are
* not listed by request.getAttributeNames(), so SnoopServlet
* does not see them. Delete attributes before result comparison. */
desc.getAttributes().clear();
result.compare(desc);
validateResponseEnd(ajpClient.readMessage(), true);
}
@Test
public void testServerName() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-SERVER-NAME", "MYSERVER");
desc.putRequestInfo("REQUEST-URI", "/testServerName");
doSnoopTest(desc);
}
@Test
public void testServerPort() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-SERVER-PORT", "8888");
desc.putRequestInfo("REQUEST-URI", "/testServerPort");
doSnoopTest(desc);
}
@Test
public void testLocalAddr() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-LOCAL-ADDR", "10.3.2.1");
desc.putRequestInfo("REQUEST-URI", "/testLocalAddr");
doSnoopTest(desc);
}
@Test
public void testRemoteHost() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-REMOTE-HOST", "MYCLIENT");
desc.putRequestInfo("REQUEST-URI", "/testRemoteHost");
doSnoopTest(desc);
}
@Test
public void testRemoteAddr() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-REMOTE-ADDR", "10.1.2.3");
desc.putRequestInfo("REQUEST-URI", "/testRemoteAddr");
doSnoopTest(desc);
}
@Test
public void testRemotePort() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-REMOTE-PORT", "34567");
desc.putRequestInfo("REQUEST-URI", "/testRemotePort");
doSnoopTest(desc);
}
@Test
public void testMethod() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-METHOD", "LOCK");
desc.putRequestInfo("REQUEST-URI", "/testMethod");
doSnoopTest(desc);
}
@Test
public void testUri() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-URI", "/a/b/c");
doSnoopTest(desc);
}
@Test
public void testProtocol() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-PROTOCOL", "HTTP/1.x");
desc.putRequestInfo("REQUEST-URI", "/testProtocol");
doSnoopTest(desc);
}
@Test
public void testSecure() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-IS-SECURE", "true");
desc.putRequestInfo("REQUEST-URI", "/testSecure");
doSnoopTest(desc);
}
@Test
public void testQueryString() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-QUERY-STRING", "p1=1&p2=12&p3=123");
desc.putRequestInfo("REQUEST-URI", "/testQueryString");
doSnoopTest(desc);
}
@Test
public void testRemoteUser() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-REMOTE-USER", "MYUSER");
desc.putRequestInfo("REQUEST-URI", "/testRemoteUser");
doSnoopTest(desc);
}
@Test
public void testAuthType() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-AUTH-TYPE", "MyAuth");
desc.putRequestInfo("REQUEST-URI", "/testAuthType");
doSnoopTest(desc);
}
@Test
public void testOneHeader() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putHeader("MYHEADER", "MYHEADER-VALUE");
desc.putRequestInfo("REQUEST-URI", "/testOneHeader");
doSnoopTest(desc);
}
@Test
public void testOneAttribute() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putAttribute("MYATTRIBUTE", "MYATTRIBUTE-VALUE");
desc.putRequestInfo("REQUEST-URI", "/testOneAttribute");
doSnoopTest(desc);
}
@Test
public void testMulti() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-SERVER-NAME", "MYSERVER");
desc.putRequestInfo("REQUEST-SERVER-PORT", "8888");
desc.putRequestInfo("REQUEST-LOCAL-ADDR", "10.3.2.1");
desc.putRequestInfo("REQUEST-REMOTE-HOST", "MYCLIENT");
desc.putRequestInfo("REQUEST-REMOTE-ADDR", "10.1.2.3");
desc.putRequestInfo("REQUEST-REMOTE-PORT", "34567");
desc.putRequestInfo("REQUEST-METHOD", "LOCK");
desc.putRequestInfo("REQUEST-URI", "/a/b/c");
desc.putRequestInfo("REQUEST-PROTOCOL", "HTTP/1.x");
desc.putRequestInfo("REQUEST-IS-SECURE", "true");
desc.putRequestInfo("REQUEST-QUERY-STRING", "p1=1&p2=12&p3=123");
desc.putRequestInfo("REQUEST-REMOTE-USER", "MYUSER");
desc.putRequestInfo("REQUEST-AUTH-TYPE", "MyAuth");
desc.putHeader("MYHEADER1", "MYHEADER1-VALUE");
desc.putHeader("MYHEADER2", "MYHEADER2-VALUE");
desc.putAttribute("MYATTRIBUTE1", "MYATTRIBUTE-VALUE1");
desc.putAttribute("MYATTRIBUTE2", "MYATTRIBUTE-VALUE2");
doSnoopTest(desc);
}
@Test
public void testSmallBody() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-METHOD", "PUT");
desc.putRequestInfo("REQUEST-CONTENT-LENGTH", "100");
desc.putRequestInfo("REQUEST-BODY-SIZE", "100");
desc.putRequestInfo("REQUEST-URI", "/testSmallBody");
doSnoopTest(desc);
}
@Test
public void testLargeBody() throws Exception {
RequestDescriptor desc = new RequestDescriptor();
desc.putRequestInfo("REQUEST-METHOD", "PUT");
desc.putRequestInfo("REQUEST-CONTENT-LENGTH", "10000");
desc.putRequestInfo("REQUEST-BODY-SIZE", "10000");
desc.putRequestInfo("REQUEST-URI", "/testLargeBody");
doSnoopTest(desc);
}
@Test
public void testSecret() throws Exception {
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setProperty("requiredSecret", "RIGHTSECRET");
tomcat.start();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "helloWorld", new HelloWorldServlet());
ctx.addServletMappingDecoded("/", "helloWorld");
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.end();
TesterAjpMessage responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 403, "Forbidden");
//TesterAjpMessage responseBody = ajpClient.readMessage();
//validateResponseBody(responseBody, HelloWorldServlet.RESPONSE_TEXT);
validateResponseEnd(ajpClient.readMessage(), false);
ajpClient.connect();
validateCpong(ajpClient.cping());
forwardMessage = ajpClient.createForwardMessage();
forwardMessage.addAttribute(0x0C, "WRONGSECRET");
forwardMessage.end();
responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 403, "Forbidden");
//responseBody = ajpClient.readMessage();
//validateResponseBody(responseBody, HelloWorldServlet.RESPONSE_TEXT);
validateResponseEnd(ajpClient.readMessage(), false);
ajpClient.connect();
validateCpong(ajpClient.cping());
forwardMessage = ajpClient.createForwardMessage();
forwardMessage.addAttribute(0x0C, "RIGHTSECRET");
forwardMessage.end();
responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 200, "OK");
TesterAjpMessage responseBody = ajpClient.readMessage();
validateResponseBody(responseBody, HelloWorldServlet.RESPONSE_TEXT);
validateResponseEnd(ajpClient.readMessage(), true);
ajpClient.disconnect();
}
@Test
public void testKeepAlive() throws Exception {
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setProperty("connectionTimeout", "-1");
tomcat.start();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "helloWorld", new HelloWorldServlet());
ctx.addServletMappingDecoded("/", "helloWorld");
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.addHeader("X-DUMMY-HEADER", "IGNORE");
// Complete the message - no extra headers required.
forwardMessage.end();
// Two requests
for (int i = 0; i < 2; i++) {
TesterAjpMessage responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 packets: headers, body, end
validateResponseHeaders(responseHeaders, 200, "OK");
TesterAjpMessage responseBody = ajpClient.readMessage();
validateResponseBody(responseBody, HelloWorldServlet.RESPONSE_TEXT);
validateResponseEnd(ajpClient.readMessage(), true);
// Give connections plenty of time to time out
Thread.sleep(2000);
// Double check the connection is still open
validateCpong(ajpClient.cping());
}
ajpClient.disconnect();
}
@Test
public void testPost() throws Exception {
doTestPost(false, HttpServletResponse.SC_OK, "OK");
}
@Test
public void testPostMultipleContentLength() throws Exception {
// Multiple content lengths
doTestPost(true, HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
}
public void doTestPost(boolean multipleCL, int expectedStatus,
String expectedMessage) throws Exception {
getTomcatInstanceTestWebapp(false, true);
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
ajpClient.setUri("/test/echo-params.jsp");
ajpClient.setMethod("POST");
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.addHeader(0xA008, "9");
if (multipleCL) {
forwardMessage.addHeader(0xA008, "99");
}
forwardMessage.addHeader(0xA007, "application/x-www-form-urlencoded");
forwardMessage.end();
TesterAjpMessage bodyMessage =
ajpClient.createBodyMessage("test=data".getBytes());
TesterAjpMessage responseHeaders =
ajpClient.sendMessage(forwardMessage, bodyMessage);
validateResponseHeaders(responseHeaders, expectedStatus, expectedMessage);
if (expectedStatus == HttpServletResponse.SC_OK) {
// Expect 3 messages: headers, body, end for a valid request
TesterAjpMessage responseBody = ajpClient.readMessage();
validateResponseBody(responseBody, "test - data");
validateResponseEnd(ajpClient.readMessage(), true);
// Double check the connection is still open
validateCpong(ajpClient.cping());
} else {
// Expect 2 messages: headers, end for an invalid request
validateResponseEnd(ajpClient.readMessage(), false);
}
ajpClient.disconnect();
}
/*
* Bug 55453
*/
@Test
public void test304WithBody() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "bug55453", new Tester304WithBodyServlet());
ctx.addServletMappingDecoded("/", "bug55453");
tomcat.start();
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.end();
TesterAjpMessage responseHeaders =
ajpClient.sendMessage(forwardMessage, null);
// Expect 2 messages: headers, end
validateResponseHeaders(responseHeaders, 304, "Not Modified");
validateResponseEnd(ajpClient.readMessage(), true);
// Double check the connection is still open
validateCpong(ajpClient.cping());
ajpClient.disconnect();
}
@Test
public void testZeroLengthRequestBodyGetA() throws Exception {
doTestZeroLengthRequestBody("GET", true);
}
@Test
public void testZeroLengthRequestBodyGetB() throws Exception {
doTestZeroLengthRequestBody("GET", false);
}
@Test
public void testZeroLengthRequestBodyPostA() throws Exception {
doTestZeroLengthRequestBody("POST", true);
}
@Test
public void testZeroLengthRequestBodyPostB() throws Exception {
doTestZeroLengthRequestBody("POST", false);
}
private void doTestZeroLengthRequestBody(String method, boolean callAvailable)
throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
ReadBodyServlet servlet = new ReadBodyServlet(callAvailable);
Tomcat.addServlet(ctx, "ReadBody", servlet);
ctx.addServletMappingDecoded("/", "ReadBody");
tomcat.start();
SimpleAjpClient ajpClient = new SimpleAjpClient();
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
ajpClient.setMethod(method);
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.addHeader(0xA008, "0");
forwardMessage.end();
TesterAjpMessage responseHeaders =
ajpClient.sendMessage(forwardMessage, null);
// Expect 3 messages: headers, body, end
validateResponseHeaders(responseHeaders, 200, "OK");
validateResponseBody(ajpClient.readMessage(),
"Request Body length in bytes: 0");
validateResponseEnd(ajpClient.readMessage(), true);
// Double check the connection is still open
validateCpong(ajpClient.cping());
ajpClient.disconnect();
if (callAvailable) {
boolean success = true;
Iterator<Integer> itAvailable = servlet.availableList.iterator();
Iterator<Integer> itRead = servlet.readList.iterator();
while (success && itAvailable.hasNext()) {
success = ((itRead.next().intValue() > 0) == (itAvailable.next().intValue() > 0));
}
if (!success) {
Assert.fail("available() and read() results do not match.\nAvailable: "
+ servlet.availableList + "\nRead: " + servlet.readList);
}
}
}
@Test
public void testLargeResponse() throws Exception {
int ajpPacketSize = 16000;
Tomcat tomcat = getTomcatInstance();
tomcat.getConnector().setProperty("packetSize", Integer.toString(ajpPacketSize));
// No file system docBase required
Context ctx = tomcat.addContext("", null);
FixedResponseSizeServlet servlet = new FixedResponseSizeServlet(15000, 16000);
Tomcat.addServlet(ctx, "FixedResponseSizeServlet", servlet);
ctx.addServletMappingDecoded("/", "FixedResponseSizeServlet");
tomcat.start();
SimpleAjpClient ajpClient = new SimpleAjpClient(ajpPacketSize);
ajpClient.setPort(getPort());
ajpClient.connect();
validateCpong(ajpClient.cping());
ajpClient.setUri("/");
TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
forwardMessage.end();
TesterAjpMessage responseHeaders = ajpClient.sendMessage(forwardMessage);
// Expect 3 messages: headers, body, end for a valid request
validateResponseHeaders(responseHeaders, 200, "OK");
TesterAjpMessage responseBody = ajpClient.readMessage();
Assert.assertTrue(responseBody.len > 15000);
validateResponseEnd(ajpClient.readMessage(), true);
// Double check the connection is still open
validateCpong(ajpClient.cping());
ajpClient.disconnect();
}
/**
* Process response header packet and checks the status. Any other data is
* ignored.
*/
private void validateResponseHeaders(TesterAjpMessage message,
int expectedStatus, String expectedMessage) throws Exception {
// First two bytes should always be AB
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// Set the start position and read the length
message.processHeader(false);
// Check the length
Assert.assertTrue(message.len > 0);
// Should be a header message
Assert.assertEquals(0x04, message.readByte());
// Check status
Assert.assertEquals(expectedStatus, message.readInt());
// Check the reason phrase
Assert.assertEquals(expectedMessage, message.readString());
// Get the number of headers
int headerCount = message.readInt();
for (int i = 0; i < headerCount; i++) {
// Read the header name
message.readHeaderName();
// Read the header value
message.readString();
}
}
private void validateGetBody(TesterAjpMessage message) {
// First two bytes should always be AB
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// Should be a body chunk message
Assert.assertEquals(0x06, message.readByte());
}
/**
* Extract the content from a response message.
*/
private String extractResponseBody(TesterAjpMessage message)
throws Exception {
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// Set the start position and read the length
message.processHeader(false);
// Should be a body chunk message
Assert.assertEquals(0x03, message.readByte());
int len = message.readInt();
Assert.assertTrue(len > 0);
return message.readString(len);
}
/**
* Validates that the response message is valid and contains the expected
* content.
*/
private void validateResponseBody(TesterAjpMessage message,
String expectedBody) throws Exception {
String body = extractResponseBody(message);
Assert.assertTrue(body.contains(expectedBody));
}
private void validateResponseEnd(TesterAjpMessage message,
boolean expectedReuse) {
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
message.processHeader(false);
// Should be an end body message
Assert.assertEquals(0x05, message.readByte());
// Check the length
Assert.assertEquals(2, message.getLen());
boolean reuse = false;
if (message.readByte() > 0) {
reuse = true;
}
Assert.assertEquals(Boolean.valueOf(expectedReuse), Boolean.valueOf(reuse));
}
private void validateCpong(TesterAjpMessage message) throws Exception {
// First two bytes should always be AB
Assert.assertEquals((byte) 'A', message.buf[0]);
Assert.assertEquals((byte) 'B', message.buf[1]);
// CPONG should have a message length of 1
// This effectively checks the next two bytes
Assert.assertEquals(1, message.getLen());
// Data should be the value 9
Assert.assertEquals(9, message.buf[4]);
}
private static class Tester304WithBodyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setStatus(304);
resp.getWriter().print("Body not permitted for 304 response");
}
}
private static class ReadBodyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final boolean callAvailable;
final List<Integer> availableList;
final List<Integer> readList;
public ReadBodyServlet(boolean callAvailable) {
this.callAvailable = callAvailable;
this.availableList = callAvailable ? new ArrayList<Integer>() : null;
this.readList = callAvailable ? new ArrayList<Integer>() : null;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doRequest(req, resp, false);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doRequest(req, resp, true);
}
private void doRequest(HttpServletRequest request, HttpServletResponse response,
boolean isPost) throws IOException {
long readCount = 0;
try (InputStream s = request.getInputStream()) {
byte[] buf = new byte[4096];
int read;
do {
if (callAvailable) {
int available = s.available();
read = s.read(buf);
availableList.add(Integer.valueOf(available));
readList.add(Integer.valueOf(read));
} else {
read = s.read(buf);
}
if (read > 0) {
readCount += read;
}
} while (read > 0);
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
try (PrintWriter w = response.getWriter()) {
w.println("Method: " + (isPost ? "POST" : "GET") + ". Reading request body...");
w.println("Request Body length in bytes: " + readCount);
}
}
}
private static class FixedResponseSizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final int responseSize;
private final int bufferSize;
public FixedResponseSizeServlet(int responseSize, int bufferSize) {
this.responseSize = responseSize;
this.bufferSize = bufferSize;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setBufferSize(bufferSize);
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.setContentLength(responseSize);
PrintWriter pw = resp.getWriter();
for (int i = 0; i < responseSize; i++) {
pw.append('X');
}
}
}
}
|
apache/james-project | 35,906 | server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/DLPConfigurationRoutesTest.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.james.webadmin.routes;
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.requestSpecification;
import static io.restassured.RestAssured.when;
import static io.restassured.RestAssured.with;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS;
import static org.apache.james.webadmin.Constants.JSON_CONTENT_TYPE;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import java.net.InetAddress;
import org.apache.james.core.Domain;
import org.apache.james.dlp.api.DLPConfigurationStore;
import org.apache.james.dlp.eventsourcing.EventSourcingDLPConfigurationStore;
import org.apache.james.dnsservice.api.DNSService;
import org.apache.james.domainlist.api.DomainList;
import org.apache.james.domainlist.lib.DomainListConfiguration;
import org.apache.james.domainlist.memory.MemoryDomainList;
import org.apache.james.eventsourcing.eventstore.memory.InMemoryEventStore;
import org.apache.james.webadmin.WebAdminServer;
import org.apache.james.webadmin.WebAdminUtils;
import org.apache.james.webadmin.utils.JsonTransformer;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import net.javacrumbs.jsonunit.core.Option;
class DLPConfigurationRoutesTest {
private static final String DEFAULT_DOMAIN = "james.org";
private static final Domain SENDER_DOMAIN = Domain.of(DEFAULT_DOMAIN);
private static final String DOMAIN_2 = "apache.org";
private static final Domain SENDER_DOMAIN_2 = Domain.of(DOMAIN_2);
private WebAdminServer webAdminServer;
private EventSourcingDLPConfigurationStore dlpStore;
private void createServer(DLPConfigurationStore dlpConfigurationStore, DomainList domainList) {
webAdminServer = WebAdminUtils.createWebAdminServer(
new DLPConfigurationRoutes(dlpConfigurationStore, domainList, new JsonTransformer()))
.start();
requestSpecification = buildRequestSpecification(webAdminServer);
}
RequestSpecification buildRequestSpecification(WebAdminServer server) {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
return WebAdminUtils
.buildRequestSpecification(server)
.setBasePath(DLPConfigurationRoutes.BASE_PATH)
.build();
}
@BeforeEach
void setup() throws Exception {
DNSService dnsService = mock(DNSService.class);
Mockito.when(dnsService.getHostName(any())).thenReturn("localhost");
Mockito.when(dnsService.getLocalHost()).thenReturn(InetAddress.getByName("localhost"));
MemoryDomainList domainList = new MemoryDomainList(dnsService);
domainList.configure(DomainListConfiguration.builder()
.autoDetect(false)
.autoDetectIp(false)
.build());
domainList.addDomain(SENDER_DOMAIN);
domainList.addDomain(SENDER_DOMAIN_2);
dlpStore = new EventSourcingDLPConfigurationStore(new InMemoryEventStore());
createServer(dlpStore, domainList);
}
@Nested
class DefineStore {
@Test
void putShouldStoreTheConfigurations() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody).isEqualTo(storeBody);
}
@Test
void putShouldStoreTheConfigurationsWhenTargetsAreNotSpecified() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3\"," +
" \"explanation\": \"explanation 3\"" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody)
.isEqualTo(
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3\"," +
" \"explanation\": \"explanation 3\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }" +
"]}");
}
@Test
void putShouldStoreTheConfigurationsWhenExplanationNotSpecified() {
String storeBody =
"{\"rules\": [{" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3\"" +
"}]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody)
.isEqualTo(
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3\"," +
" \"explanation\": null," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }" +
"]}");
}
@Test
void putShouldReturnBadRequestWhenIdIsNotSpecified() {
String body =
"{\"rules\": [{" +
" \"expression\": \"expression 4\"," +
" \"explanation\": \"explanation 4\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
"}]}";
given()
.body(body)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(400))
.body("type", is("InvalidArgument"))
.body("message", is("JSON payload of the request is not valid"))
.body("details", containsString("'id' is mandatory"));
}
@Test
void putShouldReturnBadRequestWhenExpressionIsNotSpecified() {
String body =
"{\"rules\": [{" +
" \"id\": \"5\"," +
" \"explanation\": \"explanation 5\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
"}]}";
given()
.body(body)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(400))
.body("type", is("InvalidArgument"))
.body("message", is("JSON payload of the request is not valid"))
.body("details", containsString("'expression' is mandatory"));
}
@Test
void putShouldReturnNotFoundWhenDomainNotInList() {
String body =
"[{" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
"}," +
"{" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
"}]";
given()
.body(body)
.when()
.put("strange.com")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("'strange.com' is not managed by this James server"));
}
@Test
void putShouldReturnBadRequestWhenDomainIsNotValid() {
String body =
"[{" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
"}," +
"{" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
"}]";
given()
.body(body)
.when()
.put("dr@strange.com")
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.BAD_REQUEST_400))
.body("type", is("InvalidArgument"))
.body("message", is("Invalid arguments supplied in the user request"))
.body("details", is("Domain parts ASCII chars must be a-z A-Z 0-9 - or _ in dr@strange.com"));
}
@Test
void putShouldUpdateTheConfigurations() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }," +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3\"," +
" \"explanation\": \"explanation 3\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": true" +
" }]}";
String updatedBody =
"{\"rules\": [" +
" {" +
" \"id\": \"4\"," +
" \"expression\": \"expression 4\"," +
" \"explanation\": \"explanation 4\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }," +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"expression 3 updated\"," +
" \"explanation\": \"explanation 3 updated\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": true" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
given()
.body(updatedBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody)
.when(Option.IGNORING_ARRAY_ORDER)
.isEqualTo(updatedBody);
}
@Test
void putShouldRejectDuplicatedIds() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 3\"," +
" \"explanation\": \"explanation 3\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": true" +
" }]}";
given()
.body(storeBody).log().ifValidationFails()
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.BAD_REQUEST_400))
.body("type", is("InvalidArgument"))
.body("message", is("'id' duplicates are not allowed in DLP rules"));
}
@Test
void putShouldClearTheConfigurationsWhenNoRule() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
String updatedBody = "{\"rules\": []}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
given()
.body(updatedBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody).isEqualTo(updatedBody);
}
}
@Nested
class DefineClear {
@Test
void deleteShouldRemoveTheConfigurations() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
when()
.delete(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody).isEqualTo("{\"rules\":[]}");
}
@Test
void deleteShouldRemoveOnlyConfigurationsFromCorrespondingDomain() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String storeDomain2Body =
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"apache.org\"," +
" \"targetsSender\": true" +
" }" +
"]}";
given()
.body(storeDomain2Body)
.when()
.put(DOMAIN_2)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
when()
.delete(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String retrievedBody = with()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBody).isEqualTo("{\"rules\":[]}");
String retrievedBodyDomain2 = when()
.get(DOMAIN_2)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body().asString();
assertThatJson(retrievedBodyDomain2)
.isEqualTo(
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"apache.org\"," +
" \"explanation\": null," +
" \"targetsSender\": true," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }" +
"]}");
}
@Test
void deleteShouldReturnNotFoundWhenDomainNotInList() {
when()
.delete("strange.com")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("'strange.com' is not managed by this James server"));
}
@Test
void deleteShouldReturnBadRequestWhenDomainIsNotValid() {
when()
.delete("dr@strange.com")
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.BAD_REQUEST_400))
.body("type", is("InvalidArgument"))
.body("message", is("Invalid arguments supplied in the user request"))
.body("details", is("Domain parts ASCII chars must be a-z A-Z 0-9 - or _ in dr@strange.com"));
}
}
@Nested
class DefineList {
@Test
void getShouldReturnOK() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }" +
"]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
when()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON);
}
@Test
void getShouldReturnABody() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String body = when()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body()
.asString();
assertThatJson(body).isEqualTo(
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }" +
"]}");
}
@Test
void getShouldReturnAnEmptyBodyWhenDLPStoreIsEmpty() {
String storeBody = "{\"rules\": []}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String body = when()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body()
.asString();
assertThatJson(body).isEqualTo("{\"rules\":[]}");
}
@Test
void getShouldReturnOnlyConfigurationsFromCorrespondingDomain() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String storeDomain2Body =
"{\"rules\": [" +
" {" +
" \"id\": \"3\"," +
" \"expression\": \"apache.org\"," +
" \"targetsSender\": true" +
" }" +
"]}";
given()
.body(storeDomain2Body)
.when()
.put(DOMAIN_2)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
String body = when()
.get(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body()
.asString();
assertThatJson(body).isEqualTo(
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"james.org\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": false," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }" +
"]}");
}
@Test
void getShouldReturnNotFoundWhenDomainNotInList() {
when()
.get("strange.com")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("'strange.com' is not managed by this James server"));
}
@Test
void getShouldReturnBadRequestWhenDomainIsNotValid() {
when()
.get("dr@strange.com")
.then()
.statusCode(HttpStatus.BAD_REQUEST_400)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.BAD_REQUEST_400))
.body("type", is("InvalidArgument"))
.body("message", is("Invalid arguments supplied in the user request"))
.body("details", is("Domain parts ASCII chars must be a-z A-Z 0-9 - or _ in dr@strange.com"));
}
}
@Nested
class DefineFetch {
@Test
void fetchShouldBeOK() {
storeRules();
String jsonAsString =
when()
.get(DEFAULT_DOMAIN + "/rules/1")
.then()
.statusCode(HttpStatus.OK_200)
.contentType(ContentType.JSON)
.extract()
.body()
.asString();
assertThatJson(jsonAsString)
.when(IGNORING_ARRAY_ORDER)
.when(IGNORING_EXTRA_FIELDS)
.isEqualTo("{" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
"}");
}
@Test
void fetchOnUnknownDomainShouldBe404() {
storeRules();
when()
.get("strange.com/rules/1")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("'strange.com' is not managed by this James server"));
}
@Test
void fetchOnUnknownDomainAndRuleShouldBe404() {
when()
.get("strange.com/rules/666")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("'strange.com' is not managed by this James server"));
}
@Test
void fetchOnUnknownRuleIdShouldBe404() {
storeRules();
when()
.get(DEFAULT_DOMAIN + "/rules/666")
.then()
.statusCode(HttpStatus.NOT_FOUND_404)
.contentType(JSON_CONTENT_TYPE)
.body("statusCode", is(HttpStatus.NOT_FOUND_404))
.body("type", is("InvalidArgument"))
.body("message", is("There is no rule '666' for '" + DEFAULT_DOMAIN + "' managed by this James server"));
}
private void storeRules() {
String storeBody =
"{\"rules\": [" +
" {" +
" \"id\": \"1\"," +
" \"expression\": \"expression 1\"," +
" \"explanation\": \"explanation 1\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": true," +
" \"targetsContent\": true" +
" }," +
" {" +
" \"id\": \"2\"," +
" \"expression\": \"expression 2\"," +
" \"explanation\": \"explanation 2\"," +
" \"targetsSender\": true," +
" \"targetsRecipients\": false," +
" \"targetsContent\": false" +
" }]}";
given()
.body(storeBody)
.when()
.put(DEFAULT_DOMAIN)
.then()
.statusCode(HttpStatus.NO_CONTENT_204);
}
}
} |
googleapis/google-cloud-java | 38,327 | java-redis-cluster/google-cloud-redis-cluster/src/main/java/com/google/cloud/redis/cluster/v1beta1/stub/GrpcCloudRedisClusterStub.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.redis.cluster.v1beta1.stub;
import static com.google.cloud.redis.cluster.v1beta1.CloudRedisClusterClient.ListBackupCollectionsPagedResponse;
import static com.google.cloud.redis.cluster.v1beta1.CloudRedisClusterClient.ListBackupsPagedResponse;
import static com.google.cloud.redis.cluster.v1beta1.CloudRedisClusterClient.ListClustersPagedResponse;
import static com.google.cloud.redis.cluster.v1beta1.CloudRedisClusterClient.ListLocationsPagedResponse;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.cloud.redis.cluster.v1beta1.Backup;
import com.google.cloud.redis.cluster.v1beta1.BackupClusterRequest;
import com.google.cloud.redis.cluster.v1beta1.BackupCollection;
import com.google.cloud.redis.cluster.v1beta1.CertificateAuthority;
import com.google.cloud.redis.cluster.v1beta1.Cluster;
import com.google.cloud.redis.cluster.v1beta1.CreateClusterRequest;
import com.google.cloud.redis.cluster.v1beta1.DeleteBackupRequest;
import com.google.cloud.redis.cluster.v1beta1.DeleteClusterRequest;
import com.google.cloud.redis.cluster.v1beta1.ExportBackupRequest;
import com.google.cloud.redis.cluster.v1beta1.GetBackupCollectionRequest;
import com.google.cloud.redis.cluster.v1beta1.GetBackupRequest;
import com.google.cloud.redis.cluster.v1beta1.GetClusterCertificateAuthorityRequest;
import com.google.cloud.redis.cluster.v1beta1.GetClusterRequest;
import com.google.cloud.redis.cluster.v1beta1.ListBackupCollectionsRequest;
import com.google.cloud.redis.cluster.v1beta1.ListBackupCollectionsResponse;
import com.google.cloud.redis.cluster.v1beta1.ListBackupsRequest;
import com.google.cloud.redis.cluster.v1beta1.ListBackupsResponse;
import com.google.cloud.redis.cluster.v1beta1.ListClustersRequest;
import com.google.cloud.redis.cluster.v1beta1.ListClustersResponse;
import com.google.cloud.redis.cluster.v1beta1.RescheduleClusterMaintenanceRequest;
import com.google.cloud.redis.cluster.v1beta1.UpdateClusterRequest;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.GrpcOperationsStub;
import com.google.protobuf.Any;
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 CloudRedisCluster service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class GrpcCloudRedisClusterStub extends CloudRedisClusterStub {
private static final MethodDescriptor<ListClustersRequest, ListClustersResponse>
listClustersMethodDescriptor =
MethodDescriptor.<ListClustersRequest, ListClustersResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/ListClusters")
.setRequestMarshaller(ProtoUtils.marshaller(ListClustersRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListClustersResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetClusterRequest, Cluster> getClusterMethodDescriptor =
MethodDescriptor.<GetClusterRequest, Cluster>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.redis.cluster.v1beta1.CloudRedisCluster/GetCluster")
.setRequestMarshaller(ProtoUtils.marshaller(GetClusterRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Cluster.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<UpdateClusterRequest, Operation>
updateClusterMethodDescriptor =
MethodDescriptor.<UpdateClusterRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/UpdateCluster")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateClusterRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<DeleteClusterRequest, Operation>
deleteClusterMethodDescriptor =
MethodDescriptor.<DeleteClusterRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/DeleteCluster")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteClusterRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateClusterRequest, Operation>
createClusterMethodDescriptor =
MethodDescriptor.<CreateClusterRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/CreateCluster")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateClusterRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetClusterCertificateAuthorityRequest, CertificateAuthority>
getClusterCertificateAuthorityMethodDescriptor =
MethodDescriptor.<GetClusterCertificateAuthorityRequest, CertificateAuthority>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/GetClusterCertificateAuthority")
.setRequestMarshaller(
ProtoUtils.marshaller(GetClusterCertificateAuthorityRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(CertificateAuthority.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<RescheduleClusterMaintenanceRequest, Operation>
rescheduleClusterMaintenanceMethodDescriptor =
MethodDescriptor.<RescheduleClusterMaintenanceRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/RescheduleClusterMaintenance")
.setRequestMarshaller(
ProtoUtils.marshaller(RescheduleClusterMaintenanceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListBackupCollectionsRequest, ListBackupCollectionsResponse>
listBackupCollectionsMethodDescriptor =
MethodDescriptor.<ListBackupCollectionsRequest, ListBackupCollectionsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/ListBackupCollections")
.setRequestMarshaller(
ProtoUtils.marshaller(ListBackupCollectionsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListBackupCollectionsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetBackupCollectionRequest, BackupCollection>
getBackupCollectionMethodDescriptor =
MethodDescriptor.<GetBackupCollectionRequest, BackupCollection>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/GetBackupCollection")
.setRequestMarshaller(
ProtoUtils.marshaller(GetBackupCollectionRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(BackupCollection.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListBackupsRequest, ListBackupsResponse>
listBackupsMethodDescriptor =
MethodDescriptor.<ListBackupsRequest, ListBackupsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.redis.cluster.v1beta1.CloudRedisCluster/ListBackups")
.setRequestMarshaller(ProtoUtils.marshaller(ListBackupsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListBackupsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetBackupRequest, Backup> getBackupMethodDescriptor =
MethodDescriptor.<GetBackupRequest, Backup>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.redis.cluster.v1beta1.CloudRedisCluster/GetBackup")
.setRequestMarshaller(ProtoUtils.marshaller(GetBackupRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Backup.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<DeleteBackupRequest, Operation>
deleteBackupMethodDescriptor =
MethodDescriptor.<DeleteBackupRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/DeleteBackup")
.setRequestMarshaller(ProtoUtils.marshaller(DeleteBackupRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ExportBackupRequest, Operation>
exportBackupMethodDescriptor =
MethodDescriptor.<ExportBackupRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/ExportBackup")
.setRequestMarshaller(ProtoUtils.marshaller(ExportBackupRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<BackupClusterRequest, Operation>
backupClusterMethodDescriptor =
MethodDescriptor.<BackupClusterRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.redis.cluster.v1beta1.CloudRedisCluster/BackupCluster")
.setRequestMarshaller(
ProtoUtils.marshaller(BackupClusterRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListLocationsRequest, ListLocationsResponse>
listLocationsMethodDescriptor =
MethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.location.Locations/ListLocations")
.setRequestMarshaller(
ProtoUtils.marshaller(ListLocationsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListLocationsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor =
MethodDescriptor.<GetLocationRequest, Location>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.location.Locations/GetLocation")
.setRequestMarshaller(ProtoUtils.marshaller(GetLocationRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Location.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private final UnaryCallable<ListClustersRequest, ListClustersResponse> listClustersCallable;
private final UnaryCallable<ListClustersRequest, ListClustersPagedResponse>
listClustersPagedCallable;
private final UnaryCallable<GetClusterRequest, Cluster> getClusterCallable;
private final UnaryCallable<UpdateClusterRequest, Operation> updateClusterCallable;
private final OperationCallable<UpdateClusterRequest, Cluster, Any>
updateClusterOperationCallable;
private final UnaryCallable<DeleteClusterRequest, Operation> deleteClusterCallable;
private final OperationCallable<DeleteClusterRequest, Empty, Any> deleteClusterOperationCallable;
private final UnaryCallable<CreateClusterRequest, Operation> createClusterCallable;
private final OperationCallable<CreateClusterRequest, Cluster, Any>
createClusterOperationCallable;
private final UnaryCallable<GetClusterCertificateAuthorityRequest, CertificateAuthority>
getClusterCertificateAuthorityCallable;
private final UnaryCallable<RescheduleClusterMaintenanceRequest, Operation>
rescheduleClusterMaintenanceCallable;
private final OperationCallable<RescheduleClusterMaintenanceRequest, Cluster, Any>
rescheduleClusterMaintenanceOperationCallable;
private final UnaryCallable<ListBackupCollectionsRequest, ListBackupCollectionsResponse>
listBackupCollectionsCallable;
private final UnaryCallable<ListBackupCollectionsRequest, ListBackupCollectionsPagedResponse>
listBackupCollectionsPagedCallable;
private final UnaryCallable<GetBackupCollectionRequest, BackupCollection>
getBackupCollectionCallable;
private final UnaryCallable<ListBackupsRequest, ListBackupsResponse> listBackupsCallable;
private final UnaryCallable<ListBackupsRequest, ListBackupsPagedResponse>
listBackupsPagedCallable;
private final UnaryCallable<GetBackupRequest, Backup> getBackupCallable;
private final UnaryCallable<DeleteBackupRequest, Operation> deleteBackupCallable;
private final OperationCallable<DeleteBackupRequest, Empty, Any> deleteBackupOperationCallable;
private final UnaryCallable<ExportBackupRequest, Operation> exportBackupCallable;
private final OperationCallable<ExportBackupRequest, Backup, Any> exportBackupOperationCallable;
private final UnaryCallable<BackupClusterRequest, Operation> backupClusterCallable;
private final OperationCallable<BackupClusterRequest, Cluster, Any>
backupClusterOperationCallable;
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 GrpcCloudRedisClusterStub create(CloudRedisClusterStubSettings settings)
throws IOException {
return new GrpcCloudRedisClusterStub(settings, ClientContext.create(settings));
}
public static final GrpcCloudRedisClusterStub create(ClientContext clientContext)
throws IOException {
return new GrpcCloudRedisClusterStub(
CloudRedisClusterStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcCloudRedisClusterStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcCloudRedisClusterStub(
CloudRedisClusterStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcCloudRedisClusterStub, 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 GrpcCloudRedisClusterStub(
CloudRedisClusterStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new GrpcCloudRedisClusterCallableFactory());
}
/**
* Constructs an instance of GrpcCloudRedisClusterStub, 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 GrpcCloudRedisClusterStub(
CloudRedisClusterStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<ListClustersRequest, ListClustersResponse> listClustersTransportSettings =
GrpcCallSettings.<ListClustersRequest, ListClustersResponse>newBuilder()
.setMethodDescriptor(listClustersMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<GetClusterRequest, Cluster> getClusterTransportSettings =
GrpcCallSettings.<GetClusterRequest, Cluster>newBuilder()
.setMethodDescriptor(getClusterMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<UpdateClusterRequest, Operation> updateClusterTransportSettings =
GrpcCallSettings.<UpdateClusterRequest, Operation>newBuilder()
.setMethodDescriptor(updateClusterMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("cluster.name", String.valueOf(request.getCluster().getName()));
return builder.build();
})
.build();
GrpcCallSettings<DeleteClusterRequest, Operation> deleteClusterTransportSettings =
GrpcCallSettings.<DeleteClusterRequest, Operation>newBuilder()
.setMethodDescriptor(deleteClusterMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateClusterRequest, Operation> createClusterTransportSettings =
GrpcCallSettings.<CreateClusterRequest, Operation>newBuilder()
.setMethodDescriptor(createClusterMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<GetClusterCertificateAuthorityRequest, CertificateAuthority>
getClusterCertificateAuthorityTransportSettings =
GrpcCallSettings
.<GetClusterCertificateAuthorityRequest, CertificateAuthority>newBuilder()
.setMethodDescriptor(getClusterCertificateAuthorityMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<RescheduleClusterMaintenanceRequest, Operation>
rescheduleClusterMaintenanceTransportSettings =
GrpcCallSettings.<RescheduleClusterMaintenanceRequest, Operation>newBuilder()
.setMethodDescriptor(rescheduleClusterMaintenanceMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<ListBackupCollectionsRequest, ListBackupCollectionsResponse>
listBackupCollectionsTransportSettings =
GrpcCallSettings
.<ListBackupCollectionsRequest, ListBackupCollectionsResponse>newBuilder()
.setMethodDescriptor(listBackupCollectionsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<GetBackupCollectionRequest, BackupCollection>
getBackupCollectionTransportSettings =
GrpcCallSettings.<GetBackupCollectionRequest, BackupCollection>newBuilder()
.setMethodDescriptor(getBackupCollectionMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<ListBackupsRequest, ListBackupsResponse> listBackupsTransportSettings =
GrpcCallSettings.<ListBackupsRequest, ListBackupsResponse>newBuilder()
.setMethodDescriptor(listBackupsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<GetBackupRequest, Backup> getBackupTransportSettings =
GrpcCallSettings.<GetBackupRequest, Backup>newBuilder()
.setMethodDescriptor(getBackupMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<DeleteBackupRequest, Operation> deleteBackupTransportSettings =
GrpcCallSettings.<DeleteBackupRequest, Operation>newBuilder()
.setMethodDescriptor(deleteBackupMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<ExportBackupRequest, Operation> exportBackupTransportSettings =
GrpcCallSettings.<ExportBackupRequest, Operation>newBuilder()
.setMethodDescriptor(exportBackupMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<BackupClusterRequest, Operation> backupClusterTransportSettings =
GrpcCallSettings.<BackupClusterRequest, Operation>newBuilder()
.setMethodDescriptor(backupClusterMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings =
GrpcCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder()
.setMethodDescriptor(listLocationsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<GetLocationRequest, Location> getLocationTransportSettings =
GrpcCallSettings.<GetLocationRequest, Location>newBuilder()
.setMethodDescriptor(getLocationMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
this.listClustersCallable =
callableFactory.createUnaryCallable(
listClustersTransportSettings, settings.listClustersSettings(), clientContext);
this.listClustersPagedCallable =
callableFactory.createPagedCallable(
listClustersTransportSettings, settings.listClustersSettings(), clientContext);
this.getClusterCallable =
callableFactory.createUnaryCallable(
getClusterTransportSettings, settings.getClusterSettings(), clientContext);
this.updateClusterCallable =
callableFactory.createUnaryCallable(
updateClusterTransportSettings, settings.updateClusterSettings(), clientContext);
this.updateClusterOperationCallable =
callableFactory.createOperationCallable(
updateClusterTransportSettings,
settings.updateClusterOperationSettings(),
clientContext,
operationsStub);
this.deleteClusterCallable =
callableFactory.createUnaryCallable(
deleteClusterTransportSettings, settings.deleteClusterSettings(), clientContext);
this.deleteClusterOperationCallable =
callableFactory.createOperationCallable(
deleteClusterTransportSettings,
settings.deleteClusterOperationSettings(),
clientContext,
operationsStub);
this.createClusterCallable =
callableFactory.createUnaryCallable(
createClusterTransportSettings, settings.createClusterSettings(), clientContext);
this.createClusterOperationCallable =
callableFactory.createOperationCallable(
createClusterTransportSettings,
settings.createClusterOperationSettings(),
clientContext,
operationsStub);
this.getClusterCertificateAuthorityCallable =
callableFactory.createUnaryCallable(
getClusterCertificateAuthorityTransportSettings,
settings.getClusterCertificateAuthoritySettings(),
clientContext);
this.rescheduleClusterMaintenanceCallable =
callableFactory.createUnaryCallable(
rescheduleClusterMaintenanceTransportSettings,
settings.rescheduleClusterMaintenanceSettings(),
clientContext);
this.rescheduleClusterMaintenanceOperationCallable =
callableFactory.createOperationCallable(
rescheduleClusterMaintenanceTransportSettings,
settings.rescheduleClusterMaintenanceOperationSettings(),
clientContext,
operationsStub);
this.listBackupCollectionsCallable =
callableFactory.createUnaryCallable(
listBackupCollectionsTransportSettings,
settings.listBackupCollectionsSettings(),
clientContext);
this.listBackupCollectionsPagedCallable =
callableFactory.createPagedCallable(
listBackupCollectionsTransportSettings,
settings.listBackupCollectionsSettings(),
clientContext);
this.getBackupCollectionCallable =
callableFactory.createUnaryCallable(
getBackupCollectionTransportSettings,
settings.getBackupCollectionSettings(),
clientContext);
this.listBackupsCallable =
callableFactory.createUnaryCallable(
listBackupsTransportSettings, settings.listBackupsSettings(), clientContext);
this.listBackupsPagedCallable =
callableFactory.createPagedCallable(
listBackupsTransportSettings, settings.listBackupsSettings(), clientContext);
this.getBackupCallable =
callableFactory.createUnaryCallable(
getBackupTransportSettings, settings.getBackupSettings(), clientContext);
this.deleteBackupCallable =
callableFactory.createUnaryCallable(
deleteBackupTransportSettings, settings.deleteBackupSettings(), clientContext);
this.deleteBackupOperationCallable =
callableFactory.createOperationCallable(
deleteBackupTransportSettings,
settings.deleteBackupOperationSettings(),
clientContext,
operationsStub);
this.exportBackupCallable =
callableFactory.createUnaryCallable(
exportBackupTransportSettings, settings.exportBackupSettings(), clientContext);
this.exportBackupOperationCallable =
callableFactory.createOperationCallable(
exportBackupTransportSettings,
settings.exportBackupOperationSettings(),
clientContext,
operationsStub);
this.backupClusterCallable =
callableFactory.createUnaryCallable(
backupClusterTransportSettings, settings.backupClusterSettings(), clientContext);
this.backupClusterOperationCallable =
callableFactory.createOperationCallable(
backupClusterTransportSettings,
settings.backupClusterOperationSettings(),
clientContext,
operationsStub);
this.listLocationsCallable =
callableFactory.createUnaryCallable(
listLocationsTransportSettings, settings.listLocationsSettings(), clientContext);
this.listLocationsPagedCallable =
callableFactory.createPagedCallable(
listLocationsTransportSettings, settings.listLocationsSettings(), clientContext);
this.getLocationCallable =
callableFactory.createUnaryCallable(
getLocationTransportSettings, settings.getLocationSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<ListClustersRequest, ListClustersResponse> listClustersCallable() {
return listClustersCallable;
}
@Override
public UnaryCallable<ListClustersRequest, ListClustersPagedResponse> listClustersPagedCallable() {
return listClustersPagedCallable;
}
@Override
public UnaryCallable<GetClusterRequest, Cluster> getClusterCallable() {
return getClusterCallable;
}
@Override
public UnaryCallable<UpdateClusterRequest, Operation> updateClusterCallable() {
return updateClusterCallable;
}
@Override
public OperationCallable<UpdateClusterRequest, Cluster, Any> updateClusterOperationCallable() {
return updateClusterOperationCallable;
}
@Override
public UnaryCallable<DeleteClusterRequest, Operation> deleteClusterCallable() {
return deleteClusterCallable;
}
@Override
public OperationCallable<DeleteClusterRequest, Empty, Any> deleteClusterOperationCallable() {
return deleteClusterOperationCallable;
}
@Override
public UnaryCallable<CreateClusterRequest, Operation> createClusterCallable() {
return createClusterCallable;
}
@Override
public OperationCallable<CreateClusterRequest, Cluster, Any> createClusterOperationCallable() {
return createClusterOperationCallable;
}
@Override
public UnaryCallable<GetClusterCertificateAuthorityRequest, CertificateAuthority>
getClusterCertificateAuthorityCallable() {
return getClusterCertificateAuthorityCallable;
}
@Override
public UnaryCallable<RescheduleClusterMaintenanceRequest, Operation>
rescheduleClusterMaintenanceCallable() {
return rescheduleClusterMaintenanceCallable;
}
@Override
public OperationCallable<RescheduleClusterMaintenanceRequest, Cluster, Any>
rescheduleClusterMaintenanceOperationCallable() {
return rescheduleClusterMaintenanceOperationCallable;
}
@Override
public UnaryCallable<ListBackupCollectionsRequest, ListBackupCollectionsResponse>
listBackupCollectionsCallable() {
return listBackupCollectionsCallable;
}
@Override
public UnaryCallable<ListBackupCollectionsRequest, ListBackupCollectionsPagedResponse>
listBackupCollectionsPagedCallable() {
return listBackupCollectionsPagedCallable;
}
@Override
public UnaryCallable<GetBackupCollectionRequest, BackupCollection> getBackupCollectionCallable() {
return getBackupCollectionCallable;
}
@Override
public UnaryCallable<ListBackupsRequest, ListBackupsResponse> listBackupsCallable() {
return listBackupsCallable;
}
@Override
public UnaryCallable<ListBackupsRequest, ListBackupsPagedResponse> listBackupsPagedCallable() {
return listBackupsPagedCallable;
}
@Override
public UnaryCallable<GetBackupRequest, Backup> getBackupCallable() {
return getBackupCallable;
}
@Override
public UnaryCallable<DeleteBackupRequest, Operation> deleteBackupCallable() {
return deleteBackupCallable;
}
@Override
public OperationCallable<DeleteBackupRequest, Empty, Any> deleteBackupOperationCallable() {
return deleteBackupOperationCallable;
}
@Override
public UnaryCallable<ExportBackupRequest, Operation> exportBackupCallable() {
return exportBackupCallable;
}
@Override
public OperationCallable<ExportBackupRequest, Backup, Any> exportBackupOperationCallable() {
return exportBackupOperationCallable;
}
@Override
public UnaryCallable<BackupClusterRequest, Operation> backupClusterCallable() {
return backupClusterCallable;
}
@Override
public OperationCallable<BackupClusterRequest, Cluster, Any> backupClusterOperationCallable() {
return backupClusterOperationCallable;
}
@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);
}
}
|
googleapis/google-cloud-java | 38,203 | java-dialogflow/grpc-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/GeneratorsGrpc.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dialogflow.v2beta1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/dialogflow/v2beta1/generator.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class GeneratorsGrpc {
private GeneratorsGrpc() {}
public static final java.lang.String SERVICE_NAME = "google.cloud.dialogflow.v2beta1.Generators";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getCreateGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateGenerator",
requestType = com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getCreateGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getCreateGeneratorMethod;
if ((getCreateGeneratorMethod = GeneratorsGrpc.getCreateGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getCreateGeneratorMethod = GeneratorsGrpc.getCreateGeneratorMethod) == null) {
GeneratorsGrpc.getCreateGeneratorMethod =
getCreateGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.Generator.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("CreateGenerator"))
.build();
}
}
}
return getCreateGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getGetGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetGenerator",
requestType = com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getGetGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getGetGeneratorMethod;
if ((getGetGeneratorMethod = GeneratorsGrpc.getGetGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getGetGeneratorMethod = GeneratorsGrpc.getGetGeneratorMethod) == null) {
GeneratorsGrpc.getGetGeneratorMethod =
getGetGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.Generator.getDefaultInstance()))
.setSchemaDescriptor(new GeneratorsMethodDescriptorSupplier("GetGenerator"))
.build();
}
}
}
return getGetGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest,
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
getListGeneratorsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListGenerators",
requestType = com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest,
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
getListGeneratorsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest,
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
getListGeneratorsMethod;
if ((getListGeneratorsMethod = GeneratorsGrpc.getListGeneratorsMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getListGeneratorsMethod = GeneratorsGrpc.getListGeneratorsMethod) == null) {
GeneratorsGrpc.getListGeneratorsMethod =
getListGeneratorsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest,
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListGenerators"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse
.getDefaultInstance()))
.setSchemaDescriptor(new GeneratorsMethodDescriptorSupplier("ListGenerators"))
.build();
}
}
}
return getListGeneratorsMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteGenerator",
requestType = com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest.class,
responseType = com.google.protobuf.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod;
if ((getDeleteGeneratorMethod = GeneratorsGrpc.getDeleteGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getDeleteGeneratorMethod = GeneratorsGrpc.getDeleteGeneratorMethod) == null) {
GeneratorsGrpc.getDeleteGeneratorMethod =
getDeleteGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest,
com.google.protobuf.Empty>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.protobuf.Empty.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("DeleteGenerator"))
.build();
}
}
}
return getDeleteGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getUpdateGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UpdateGenerator",
requestType = com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getUpdateGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
getUpdateGeneratorMethod;
if ((getUpdateGeneratorMethod = GeneratorsGrpc.getUpdateGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getUpdateGeneratorMethod = GeneratorsGrpc.getUpdateGeneratorMethod) == null) {
GeneratorsGrpc.getUpdateGeneratorMethod =
getUpdateGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.Generator.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("UpdateGenerator"))
.build();
}
}
}
return getUpdateGeneratorMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static GeneratorsStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsStub>() {
@java.lang.Override
public GeneratorsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsStub(channel, callOptions);
}
};
return GeneratorsStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static GeneratorsBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingV2Stub>() {
@java.lang.Override
public GeneratorsBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingV2Stub(channel, callOptions);
}
};
return GeneratorsBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static GeneratorsBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingStub>() {
@java.lang.Override
public GeneratorsBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingStub(channel, callOptions);
}
};
return GeneratorsBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static GeneratorsFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsFutureStub>() {
@java.lang.Override
public GeneratorsFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsFutureStub(channel, callOptions);
}
};
return GeneratorsFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Creates a generator.
* </pre>
*/
default void createGenerator(
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCreateGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Retrieves a generator.
* </pre>
*/
default void getGenerator(
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getGetGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Lists generators.
* </pre>
*/
default void listGenerators(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListGeneratorsMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes a generator.
* </pre>
*/
default void deleteGenerator(
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeleteGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Updates a generator.
* </pre>
*/
default void updateGenerator(
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUpdateGeneratorMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service Generators.
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public abstract static class GeneratorsImplBase implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return GeneratorsGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service Generators.
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public static final class GeneratorsStub extends io.grpc.stub.AbstractAsyncStub<GeneratorsStub> {
private GeneratorsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsStub(channel, callOptions);
}
/**
*
*
* <pre>
* Creates a generator.
* </pre>
*/
public void createGenerator(
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreateGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Retrieves a generator.
* </pre>
*/
public void getGenerator(
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Lists generators.
* </pre>
*/
public void listGenerators(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListGeneratorsMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Deletes a generator.
* </pre>
*/
public void deleteGenerator(
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Updates a generator.
* </pre>
*/
public void updateGenerator(
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUpdateGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service Generators.
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public static final class GeneratorsBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<GeneratorsBlockingV2Stub> {
private GeneratorsBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Creates a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator createGenerator(
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator getGenerator(
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Lists generators.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse listGenerators(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListGeneratorsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a generator.
* </pre>
*/
public com.google.protobuf.Empty deleteGenerator(
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator updateGenerator(
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateGeneratorMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service Generators.
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public static final class GeneratorsBlockingStub
extends io.grpc.stub.AbstractBlockingStub<GeneratorsBlockingStub> {
private GeneratorsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Creates a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator createGenerator(
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator getGenerator(
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Lists generators.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse listGenerators(
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListGeneratorsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a generator.
* </pre>
*/
public com.google.protobuf.Empty deleteGenerator(
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates a generator.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.Generator updateGenerator(
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateGeneratorMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service Generators.
*
* <pre>
* Generator Service for LLM powered Agent Assist. This service manages the
* configurations of user owned Generators, such as description, context and
* instruction, input/output format, etc. The generator resources will be used
* inside a conversation and will be triggered by TriggerEvent to query LLM for
* answers.
* </pre>
*/
public static final class GeneratorsFutureStub
extends io.grpc.stub.AbstractFutureStub<GeneratorsFutureStub> {
private GeneratorsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Creates a generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.Generator>
createGenerator(com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreateGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Retrieves a generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.Generator>
getGenerator(com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Lists generators.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>
listGenerators(com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListGeneratorsMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes a generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>
deleteGenerator(com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Updates a generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.Generator>
updateGenerator(com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUpdateGeneratorMethod(), getCallOptions()), request);
}
}
private static final int METHODID_CREATE_GENERATOR = 0;
private static final int METHODID_GET_GENERATOR = 1;
private static final int METHODID_LIST_GENERATORS = 2;
private static final int METHODID_DELETE_GENERATOR = 3;
private static final int METHODID_UPDATE_GENERATOR = 4;
private static final class MethodHandlers<Req, Resp>
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CREATE_GENERATOR:
serviceImpl.createGenerator(
(com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>)
responseObserver);
break;
case METHODID_GET_GENERATOR:
serviceImpl.getGenerator(
(com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>)
responseObserver);
break;
case METHODID_LIST_GENERATORS:
serviceImpl.listGenerators(
(com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>)
responseObserver);
break;
case METHODID_DELETE_GENERATOR:
serviceImpl.deleteGenerator(
(com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver);
break;
case METHODID_UPDATE_GENERATOR:
serviceImpl.updateGenerator(
(com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.Generator>)
responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getCreateGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.CreateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>(
service, METHODID_CREATE_GENERATOR)))
.addMethod(
getGetGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.GetGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>(
service, METHODID_GET_GENERATOR)))
.addMethod(
getListGeneratorsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.ListGeneratorsRequest,
com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse>(
service, METHODID_LIST_GENERATORS)))
.addMethod(
getDeleteGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.DeleteGeneratorRequest,
com.google.protobuf.Empty>(service, METHODID_DELETE_GENERATOR)))
.addMethod(
getUpdateGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.UpdateGeneratorRequest,
com.google.cloud.dialogflow.v2beta1.Generator>(
service, METHODID_UPDATE_GENERATOR)))
.build();
}
private abstract static class GeneratorsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
GeneratorsBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.dialogflow.v2beta1.GeneratorProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Generators");
}
}
private static final class GeneratorsFileDescriptorSupplier
extends GeneratorsBaseDescriptorSupplier {
GeneratorsFileDescriptorSupplier() {}
}
private static final class GeneratorsMethodDescriptorSupplier
extends GeneratorsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
GeneratorsMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (GeneratorsGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new GeneratorsFileDescriptorSupplier())
.addMethod(getCreateGeneratorMethod())
.addMethod(getGetGeneratorMethod())
.addMethod(getListGeneratorsMethod())
.addMethod(getDeleteGeneratorMethod())
.addMethod(getUpdateGeneratorMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 38,315 | java-data-fusion/google-cloud-data-fusion/src/main/java/com/google/cloud/datafusion/v1/stub/DataFusionStubSettings.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.datafusion.v1.stub;
import static com.google.cloud.datafusion.v1.DataFusionClient.ListAvailableVersionsPagedResponse;
import static com.google.cloud.datafusion.v1.DataFusionClient.ListInstancesPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.ProtoOperationTransformers;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.datafusion.v1.CreateInstanceRequest;
import com.google.cloud.datafusion.v1.DeleteInstanceRequest;
import com.google.cloud.datafusion.v1.GetInstanceRequest;
import com.google.cloud.datafusion.v1.Instance;
import com.google.cloud.datafusion.v1.ListAvailableVersionsRequest;
import com.google.cloud.datafusion.v1.ListAvailableVersionsResponse;
import com.google.cloud.datafusion.v1.ListInstancesRequest;
import com.google.cloud.datafusion.v1.ListInstancesResponse;
import com.google.cloud.datafusion.v1.OperationMetadata;
import com.google.cloud.datafusion.v1.RestartInstanceRequest;
import com.google.cloud.datafusion.v1.UpdateInstanceRequest;
import com.google.cloud.datafusion.v1.Version;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link DataFusionStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (datafusion.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of getInstance:
*
* <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
* DataFusionStubSettings.Builder dataFusionSettingsBuilder = DataFusionStubSettings.newBuilder();
* dataFusionSettingsBuilder
* .getInstanceSettings()
* .setRetrySettings(
* dataFusionSettingsBuilder
* .getInstanceSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* DataFusionStubSettings dataFusionSettings = dataFusionSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for createInstance:
*
* <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
* DataFusionStubSettings.Builder dataFusionSettingsBuilder = DataFusionStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* dataFusionSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class DataFusionStubSettings extends StubSettings<DataFusionStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build();
private final PagedCallSettings<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>
listAvailableVersionsSettings;
private final PagedCallSettings<
ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>
listInstancesSettings;
private final UnaryCallSettings<GetInstanceRequest, Instance> getInstanceSettings;
private final UnaryCallSettings<CreateInstanceRequest, Operation> createInstanceSettings;
private final OperationCallSettings<CreateInstanceRequest, Instance, OperationMetadata>
createInstanceOperationSettings;
private final UnaryCallSettings<DeleteInstanceRequest, Operation> deleteInstanceSettings;
private final OperationCallSettings<DeleteInstanceRequest, Empty, OperationMetadata>
deleteInstanceOperationSettings;
private final UnaryCallSettings<UpdateInstanceRequest, Operation> updateInstanceSettings;
private final OperationCallSettings<UpdateInstanceRequest, Instance, OperationMetadata>
updateInstanceOperationSettings;
private final UnaryCallSettings<RestartInstanceRequest, Operation> restartInstanceSettings;
private final OperationCallSettings<RestartInstanceRequest, Instance, OperationMetadata>
restartInstanceOperationSettings;
private static final PagedListDescriptor<
ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version>
LIST_AVAILABLE_VERSIONS_PAGE_STR_DESC =
new PagedListDescriptor<
ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListAvailableVersionsRequest injectToken(
ListAvailableVersionsRequest payload, String token) {
return ListAvailableVersionsRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListAvailableVersionsRequest injectPageSize(
ListAvailableVersionsRequest payload, int pageSize) {
return ListAvailableVersionsRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListAvailableVersionsRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListAvailableVersionsResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Version> extractResources(ListAvailableVersionsResponse payload) {
return payload.getAvailableVersionsList();
}
};
private static final PagedListDescriptor<ListInstancesRequest, ListInstancesResponse, Instance>
LIST_INSTANCES_PAGE_STR_DESC =
new PagedListDescriptor<ListInstancesRequest, ListInstancesResponse, Instance>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListInstancesRequest injectToken(ListInstancesRequest payload, String token) {
return ListInstancesRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListInstancesRequest injectPageSize(ListInstancesRequest payload, int pageSize) {
return ListInstancesRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListInstancesRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListInstancesResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Instance> extractResources(ListInstancesResponse payload) {
return payload.getInstancesList();
}
};
private static final PagedListResponseFactory<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>
LIST_AVAILABLE_VERSIONS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>() {
@Override
public ApiFuture<ListAvailableVersionsPagedResponse> getFuturePagedResponse(
UnaryCallable<ListAvailableVersionsRequest, ListAvailableVersionsResponse> callable,
ListAvailableVersionsRequest request,
ApiCallContext context,
ApiFuture<ListAvailableVersionsResponse> futureResponse) {
PageContext<ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version>
pageContext =
PageContext.create(
callable, LIST_AVAILABLE_VERSIONS_PAGE_STR_DESC, request, context);
return ListAvailableVersionsPagedResponse.createAsync(pageContext, futureResponse);
}
};
private static final PagedListResponseFactory<
ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>
LIST_INSTANCES_PAGE_STR_FACT =
new PagedListResponseFactory<
ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>() {
@Override
public ApiFuture<ListInstancesPagedResponse> getFuturePagedResponse(
UnaryCallable<ListInstancesRequest, ListInstancesResponse> callable,
ListInstancesRequest request,
ApiCallContext context,
ApiFuture<ListInstancesResponse> futureResponse) {
PageContext<ListInstancesRequest, ListInstancesResponse, Instance> pageContext =
PageContext.create(callable, LIST_INSTANCES_PAGE_STR_DESC, request, context);
return ListInstancesPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to listAvailableVersions. */
public PagedCallSettings<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>
listAvailableVersionsSettings() {
return listAvailableVersionsSettings;
}
/** Returns the object with the settings used for calls to listInstances. */
public PagedCallSettings<ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>
listInstancesSettings() {
return listInstancesSettings;
}
/** Returns the object with the settings used for calls to getInstance. */
public UnaryCallSettings<GetInstanceRequest, Instance> getInstanceSettings() {
return getInstanceSettings;
}
/** Returns the object with the settings used for calls to createInstance. */
public UnaryCallSettings<CreateInstanceRequest, Operation> createInstanceSettings() {
return createInstanceSettings;
}
/** Returns the object with the settings used for calls to createInstance. */
public OperationCallSettings<CreateInstanceRequest, Instance, OperationMetadata>
createInstanceOperationSettings() {
return createInstanceOperationSettings;
}
/** Returns the object with the settings used for calls to deleteInstance. */
public UnaryCallSettings<DeleteInstanceRequest, Operation> deleteInstanceSettings() {
return deleteInstanceSettings;
}
/** Returns the object with the settings used for calls to deleteInstance. */
public OperationCallSettings<DeleteInstanceRequest, Empty, OperationMetadata>
deleteInstanceOperationSettings() {
return deleteInstanceOperationSettings;
}
/** Returns the object with the settings used for calls to updateInstance. */
public UnaryCallSettings<UpdateInstanceRequest, Operation> updateInstanceSettings() {
return updateInstanceSettings;
}
/** Returns the object with the settings used for calls to updateInstance. */
public OperationCallSettings<UpdateInstanceRequest, Instance, OperationMetadata>
updateInstanceOperationSettings() {
return updateInstanceOperationSettings;
}
/** Returns the object with the settings used for calls to restartInstance. */
public UnaryCallSettings<RestartInstanceRequest, Operation> restartInstanceSettings() {
return restartInstanceSettings;
}
/** Returns the object with the settings used for calls to restartInstance. */
public OperationCallSettings<RestartInstanceRequest, Instance, OperationMetadata>
restartInstanceOperationSettings() {
return restartInstanceOperationSettings;
}
public DataFusionStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcDataFusionStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonDataFusionStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "datafusion";
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
@ObsoleteApi("Use getEndpoint() instead")
public static String getDefaultEndpoint() {
return "datafusion.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "datafusion.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default gRPC ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder()
.setMaxInboundMessageSize(Integer.MAX_VALUE);
}
/** Returns a builder for the default REST ChannelProvider for this service. */
@BetaApi
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(DataFusionStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(DataFusionStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return DataFusionStubSettings.defaultGrpcApiClientHeaderProviderBuilder();
}
/** Returns a new gRPC builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new REST builder for this class. */
public static Builder newHttpJsonBuilder() {
return Builder.createHttpJsonDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected DataFusionStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
listAvailableVersionsSettings = settingsBuilder.listAvailableVersionsSettings().build();
listInstancesSettings = settingsBuilder.listInstancesSettings().build();
getInstanceSettings = settingsBuilder.getInstanceSettings().build();
createInstanceSettings = settingsBuilder.createInstanceSettings().build();
createInstanceOperationSettings = settingsBuilder.createInstanceOperationSettings().build();
deleteInstanceSettings = settingsBuilder.deleteInstanceSettings().build();
deleteInstanceOperationSettings = settingsBuilder.deleteInstanceOperationSettings().build();
updateInstanceSettings = settingsBuilder.updateInstanceSettings().build();
updateInstanceOperationSettings = settingsBuilder.updateInstanceOperationSettings().build();
restartInstanceSettings = settingsBuilder.restartInstanceSettings().build();
restartInstanceOperationSettings = settingsBuilder.restartInstanceOperationSettings().build();
}
/** Builder for DataFusionStubSettings. */
public static class Builder extends StubSettings.Builder<DataFusionStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>
listAvailableVersionsSettings;
private final PagedCallSettings.Builder<
ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>
listInstancesSettings;
private final UnaryCallSettings.Builder<GetInstanceRequest, Instance> getInstanceSettings;
private final UnaryCallSettings.Builder<CreateInstanceRequest, Operation>
createInstanceSettings;
private final OperationCallSettings.Builder<CreateInstanceRequest, Instance, OperationMetadata>
createInstanceOperationSettings;
private final UnaryCallSettings.Builder<DeleteInstanceRequest, Operation>
deleteInstanceSettings;
private final OperationCallSettings.Builder<DeleteInstanceRequest, Empty, OperationMetadata>
deleteInstanceOperationSettings;
private final UnaryCallSettings.Builder<UpdateInstanceRequest, Operation>
updateInstanceSettings;
private final OperationCallSettings.Builder<UpdateInstanceRequest, Instance, OperationMetadata>
updateInstanceOperationSettings;
private final UnaryCallSettings.Builder<RestartInstanceRequest, Operation>
restartInstanceSettings;
private final OperationCallSettings.Builder<RestartInstanceRequest, Instance, OperationMetadata>
restartInstanceOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"no_retry_0_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_0_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
listAvailableVersionsSettings =
PagedCallSettings.newBuilder(LIST_AVAILABLE_VERSIONS_PAGE_STR_FACT);
listInstancesSettings = PagedCallSettings.newBuilder(LIST_INSTANCES_PAGE_STR_FACT);
getInstanceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createInstanceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createInstanceOperationSettings = OperationCallSettings.newBuilder();
deleteInstanceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteInstanceOperationSettings = OperationCallSettings.newBuilder();
updateInstanceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateInstanceOperationSettings = OperationCallSettings.newBuilder();
restartInstanceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
restartInstanceOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listAvailableVersionsSettings,
listInstancesSettings,
getInstanceSettings,
createInstanceSettings,
deleteInstanceSettings,
updateInstanceSettings,
restartInstanceSettings);
initDefaults(this);
}
protected Builder(DataFusionStubSettings settings) {
super(settings);
listAvailableVersionsSettings = settings.listAvailableVersionsSettings.toBuilder();
listInstancesSettings = settings.listInstancesSettings.toBuilder();
getInstanceSettings = settings.getInstanceSettings.toBuilder();
createInstanceSettings = settings.createInstanceSettings.toBuilder();
createInstanceOperationSettings = settings.createInstanceOperationSettings.toBuilder();
deleteInstanceSettings = settings.deleteInstanceSettings.toBuilder();
deleteInstanceOperationSettings = settings.deleteInstanceOperationSettings.toBuilder();
updateInstanceSettings = settings.updateInstanceSettings.toBuilder();
updateInstanceOperationSettings = settings.updateInstanceOperationSettings.toBuilder();
restartInstanceSettings = settings.restartInstanceSettings.toBuilder();
restartInstanceOperationSettings = settings.restartInstanceOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listAvailableVersionsSettings,
listInstancesSettings,
getInstanceSettings,
createInstanceSettings,
deleteInstanceSettings,
updateInstanceSettings,
restartInstanceSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder createHttpJsonDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultHttpJsonTransportProviderBuilder().build());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultHttpJsonApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.listAvailableVersionsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.listInstancesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.getInstanceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.createInstanceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.deleteInstanceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.updateInstanceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.restartInstanceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"));
builder
.createInstanceOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateInstanceRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Instance.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.deleteInstanceOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteInstanceRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Empty.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.updateInstanceOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<UpdateInstanceRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Instance.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.restartInstanceOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<RestartInstanceRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Instance.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(OperationMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to listAvailableVersions. */
public PagedCallSettings.Builder<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
ListAvailableVersionsPagedResponse>
listAvailableVersionsSettings() {
return listAvailableVersionsSettings;
}
/** Returns the builder for the settings used for calls to listInstances. */
public PagedCallSettings.Builder<
ListInstancesRequest, ListInstancesResponse, ListInstancesPagedResponse>
listInstancesSettings() {
return listInstancesSettings;
}
/** Returns the builder for the settings used for calls to getInstance. */
public UnaryCallSettings.Builder<GetInstanceRequest, Instance> getInstanceSettings() {
return getInstanceSettings;
}
/** Returns the builder for the settings used for calls to createInstance. */
public UnaryCallSettings.Builder<CreateInstanceRequest, Operation> createInstanceSettings() {
return createInstanceSettings;
}
/** Returns the builder for the settings used for calls to createInstance. */
public OperationCallSettings.Builder<CreateInstanceRequest, Instance, OperationMetadata>
createInstanceOperationSettings() {
return createInstanceOperationSettings;
}
/** Returns the builder for the settings used for calls to deleteInstance. */
public UnaryCallSettings.Builder<DeleteInstanceRequest, Operation> deleteInstanceSettings() {
return deleteInstanceSettings;
}
/** Returns the builder for the settings used for calls to deleteInstance. */
public OperationCallSettings.Builder<DeleteInstanceRequest, Empty, OperationMetadata>
deleteInstanceOperationSettings() {
return deleteInstanceOperationSettings;
}
/** Returns the builder for the settings used for calls to updateInstance. */
public UnaryCallSettings.Builder<UpdateInstanceRequest, Operation> updateInstanceSettings() {
return updateInstanceSettings;
}
/** Returns the builder for the settings used for calls to updateInstance. */
public OperationCallSettings.Builder<UpdateInstanceRequest, Instance, OperationMetadata>
updateInstanceOperationSettings() {
return updateInstanceOperationSettings;
}
/** Returns the builder for the settings used for calls to restartInstance. */
public UnaryCallSettings.Builder<RestartInstanceRequest, Operation> restartInstanceSettings() {
return restartInstanceSettings;
}
/** Returns the builder for the settings used for calls to restartInstance. */
public OperationCallSettings.Builder<RestartInstanceRequest, Instance, OperationMetadata>
restartInstanceOperationSettings() {
return restartInstanceOperationSettings;
}
@Override
public DataFusionStubSettings build() throws IOException {
return new DataFusionStubSettings(this);
}
}
}
|
oracle/graal | 38,275 | substratevm/src/com.oracle.svm.agent/src/com/oracle/svm/agent/NativeImageAgent.java | /*
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.agent;
import static com.oracle.svm.agent.NativeImageAgent.ExitCodes.AGENT_ERROR;
import static com.oracle.svm.agent.NativeImageAgent.ExitCodes.PARSE_ERROR;
import static com.oracle.svm.agent.NativeImageAgent.ExitCodes.SUCCESS;
import static com.oracle.svm.agent.NativeImageAgent.ExitCodes.USAGE_ERROR;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.ProcessProperties;
import org.graalvm.nativeimage.hosted.Feature;
import com.oracle.svm.agent.conditionalconfig.ConditionalConfigurationPartialRunWriter;
import com.oracle.svm.agent.conditionalconfig.ConditionalConfigurationWriter;
import com.oracle.svm.agent.configwithorigins.ConfigurationWithOriginsTracer;
import com.oracle.svm.agent.configwithorigins.ConfigurationWithOriginsWriter;
import com.oracle.svm.agent.configwithorigins.MethodInfoRecordKeeper;
import com.oracle.svm.agent.ignoredconfig.AgentMetaInfProcessor;
import com.oracle.svm.agent.stackaccess.EagerlyLoadedJavaStackAccess;
import com.oracle.svm.agent.stackaccess.InterceptedState;
import com.oracle.svm.agent.stackaccess.OnDemandJavaStackAccess;
import com.oracle.svm.agent.tracing.ConfigurationResultWriter;
import com.oracle.svm.agent.tracing.TraceFileWriter;
import com.oracle.svm.agent.tracing.core.Tracer;
import com.oracle.svm.agent.tracing.core.TracingResultWriter;
import com.oracle.svm.configure.ConfigurationFile;
import com.oracle.svm.configure.PredefinedClassesConfigurationParser;
import com.oracle.svm.configure.config.ConfigurationFileCollection;
import com.oracle.svm.configure.config.ConfigurationSet;
import com.oracle.svm.configure.config.conditional.ConditionalConfigurationPredicate;
import com.oracle.svm.configure.filters.ComplexFilter;
import com.oracle.svm.configure.filters.FilterConfigurationParser;
import com.oracle.svm.configure.filters.HierarchyFilterNode;
import com.oracle.svm.configure.trace.AccessAdvisor;
import com.oracle.svm.configure.trace.TraceProcessor;
import com.oracle.svm.core.jni.headers.JNIEnvironment;
import com.oracle.svm.core.jni.headers.JNIJavaVM;
import com.oracle.svm.core.jni.headers.JNIObjectHandle;
import com.oracle.svm.driver.metainf.NativeImageMetaInfWalker;
import com.oracle.svm.jvmtiagentbase.JNIHandleSet;
import com.oracle.svm.jvmtiagentbase.JvmtiAgentBase;
import com.oracle.svm.jvmtiagentbase.Support;
import com.oracle.svm.jvmtiagentbase.jvmti.JvmtiEnv;
import com.oracle.svm.jvmtiagentbase.jvmti.JvmtiEventCallbacks;
import com.oracle.svm.jvmtiagentbase.jvmti.JvmtiInterface;
import jdk.graal.compiler.phases.common.LazyValue;
public final class NativeImageAgent extends JvmtiAgentBase<NativeImageAgentJNIHandleSet> {
private static final String AGENT_NAME = "native-image-agent";
private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC");
private ScheduledThreadPoolExecutor periodicConfigWriterExecutor = null;
private Tracer tracer;
private TracingResultWriter tracingResultWriter;
private Path configOutputDirPath;
private Path configOutputLockFilePath;
private FileTime expectedConfigModifiedBefore;
Set<String> classPathEntries;
private static String getTokenValue(String token) {
return token.substring(token.indexOf('=') + 1);
}
private static boolean getBooleanTokenValue(String token) {
int equalsIndex = token.indexOf('=');
if (equalsIndex == -1) {
return true;
}
return Boolean.parseBoolean(token.substring(equalsIndex + 1));
}
private static boolean isBooleanOption(String token, String option) {
return token.equals(option) || token.startsWith(option + "=");
}
@Override
protected int getRequiredJvmtiVersion() {
return JvmtiInterface.JVMTI_VERSION_1_2;
}
@Override
protected JNIHandleSet constructJavaHandles(JNIEnvironment env) {
return new NativeImageAgentJNIHandleSet(env);
}
@Override
protected int onLoadCallback(JNIJavaVM vm, JvmtiEnv jvmti, JvmtiEventCallbacks callbacks, String options) {
String traceOutputFile = null;
String configOutputDir = null;
String ignoredEntriesFile = null;
ConfigurationFileCollection mergeConfigs = new ConfigurationFileCollection();
ConfigurationFileCollection omittedConfigs = new ConfigurationFileCollection();
boolean builtinCallerFilter = true;
boolean builtinHeuristicFilter = true;
List<String> callerFilterFiles = new ArrayList<>();
List<String> accessFilterFiles = new ArrayList<>();
boolean experimentalClassLoaderSupport = true;
boolean experimentalClassDefineSupport = false;
boolean experimentalUnsafeAllocationSupport = false;
boolean experimentalOmitClasspathConfig = false;
boolean configurationWithOrigins = false;
List<String> conditionalConfigUserPackageFilterFiles = new ArrayList<>();
List<String> conditionalConfigClassNameFilterFiles = new ArrayList<>();
boolean conditionalConfigPartialRun = false;
int configWritePeriod = -1; // in seconds
int configWritePeriodInitialDelay = 1; // in seconds
boolean trackReflectionMetadata = true;
String[] tokens = !options.isEmpty() ? options.split(",") : new String[0];
for (String token : tokens) {
if (token.startsWith("trace-output=")) {
if (traceOutputFile != null) {
return usage("cannot specify trace-output= more than once.");
}
traceOutputFile = getTokenValue(token);
} else if (token.startsWith("config-output-dir=") || token.startsWith("config-merge-dir=")) {
if (configOutputDir != null) {
return usage("cannot specify more than one of config-output-dir= or config-merge-dir=.");
}
configOutputDir = transformPath(getTokenValue(token));
if (token.startsWith("config-merge-dir=")) {
mergeConfigs.addDirectory(Paths.get(configOutputDir));
}
} else if (token.startsWith("experimental-ignored-entries-output=")) {
if (ignoredEntriesFile != null) {
return usage("cannot specify ignored-entries-output= more than once.");
}
warn("Ignored entries logging (enabled by the \"experimental-ignored-entries-output\" argument) is " +
"experimental and will be removed in the future. Do not rely on this feature.");
ignoredEntriesFile = getTokenValue(token);
} else if (token.startsWith("config-to-omit=")) {
String omittedConfigDir = getTokenValue(token);
omittedConfigDir = transformPath(omittedConfigDir);
omittedConfigs.addDirectory(Paths.get(omittedConfigDir));
} else if (isBooleanOption(token, "experimental-omit-config-from-classpath")) {
experimentalOmitClasspathConfig = getBooleanTokenValue(token);
} else if (token.startsWith("restrict-all-dir") || token.equals("restrict") || token.startsWith("restrict=")) {
warn("restrict mode is no longer supported, ignoring option: " + token);
} else if (token.equals("no-builtin-caller-filter")) {
builtinCallerFilter = false;
} else if (isBooleanOption(token, "builtin-caller-filter")) {
builtinCallerFilter = getBooleanTokenValue(token);
} else if (token.equals("no-builtin-heuristic-filter")) {
builtinHeuristicFilter = false;
} else if (isBooleanOption(token, "builtin-heuristic-filter")) {
builtinHeuristicFilter = getBooleanTokenValue(token);
} else if (isBooleanOption(token, "no-filter")) { // legacy
builtinCallerFilter = !getBooleanTokenValue(token);
builtinHeuristicFilter = builtinCallerFilter;
} else if (token.startsWith("caller-filter-file=")) {
callerFilterFiles.add(getTokenValue(token));
} else if (token.startsWith("access-filter-file=")) {
accessFilterFiles.add(getTokenValue(token));
} else if (isBooleanOption(token, "experimental-class-loader-support")) {
experimentalClassLoaderSupport = getBooleanTokenValue(token);
} else if (isBooleanOption(token, "experimental-class-define-support")) {
experimentalClassDefineSupport = getBooleanTokenValue(token);
} else if (isBooleanOption(token, "experimental-unsafe-allocation-support")) {
experimentalUnsafeAllocationSupport = getBooleanTokenValue(token);
} else if (token.startsWith("config-write-period-secs=")) {
configWritePeriod = parseIntegerOrNegative(getTokenValue(token));
if (configWritePeriod <= 0) {
return usage("config-write-period-secs must be an integer greater than 0");
}
} else if (token.startsWith("config-write-initial-delay-secs=")) {
configWritePeriodInitialDelay = parseIntegerOrNegative(getTokenValue(token));
if (configWritePeriodInitialDelay < 0) {
return usage("config-write-initial-delay-secs must be an integer greater or equal to 0");
}
} else if (isBooleanOption(token, "experimental-configuration-with-origins")) {
configurationWithOrigins = getBooleanTokenValue(token);
} else if (token.startsWith("experimental-conditional-config-filter-file=")) {
conditionalConfigUserPackageFilterFiles.add(getTokenValue(token));
} else if (token.startsWith("conditional-config-class-filter-file=")) {
conditionalConfigClassNameFilterFiles.add(getTokenValue(token));
} else if (isBooleanOption(token, "experimental-conditional-config-part")) {
conditionalConfigPartialRun = getBooleanTokenValue(token);
} else if (isBooleanOption(token, "track-reflection-metadata")) {
trackReflectionMetadata = getBooleanTokenValue(token);
} else {
return usage("unknown option: '" + token + "'.");
}
}
if (!checkJVMVersion(jvmti)) {
return USAGE_ERROR;
}
if (traceOutputFile == null && configOutputDir == null) {
configOutputDir = transformPath(AGENT_NAME + "_config-pid{pid}-{datetime}/");
inform("no output options provided, tracking dynamic accesses and writing configuration to directory: " + configOutputDir);
}
if (configurationWithOrigins && !conditionalConfigUserPackageFilterFiles.isEmpty()) {
return error(USAGE_ERROR, "The agent can only be used in either the configuration with origins mode or the predefined classes mode.");
}
if (configurationWithOrigins && !mergeConfigs.isEmpty()) {
configurationWithOrigins = false;
inform("using configuration with origins with configuration merging is currently unsupported. Disabling configuration with origins mode.");
}
if (configurationWithOrigins) {
warn("using experimental configuration with origins mode. Note that native-image cannot process these files, and this flag may change or be removed without a warning!");
}
ComplexFilter callerFilter = null;
HierarchyFilterNode callerFilterHierarchyFilterNode = null;
if (!builtinCallerFilter) {
callerFilterHierarchyFilterNode = HierarchyFilterNode.createInclusiveRoot();
callerFilter = new ComplexFilter(callerFilterHierarchyFilterNode);
}
if (!callerFilterFiles.isEmpty()) {
if (callerFilterHierarchyFilterNode == null) {
callerFilterHierarchyFilterNode = AccessAdvisor.copyBuiltinCallerFilterTree();
callerFilter = new ComplexFilter(callerFilterHierarchyFilterNode);
}
if (!parseFilterFiles(callerFilter, callerFilterFiles)) {
return PARSE_ERROR;
}
}
ComplexFilter accessFilter = null;
if (!accessFilterFiles.isEmpty()) {
accessFilter = new ComplexFilter(AccessAdvisor.copyBuiltinAccessFilterTree());
if (!parseFilterFiles(accessFilter, accessFilterFiles)) {
return PARSE_ERROR;
}
}
if (!conditionalConfigUserPackageFilterFiles.isEmpty() && conditionalConfigPartialRun) {
return error(USAGE_ERROR, "The agent can generate conditional configuration either for the current run or in the partial mode but not both at the same time.");
}
classPathEntries = new HashSet<>(Arrays.asList(getClasspathEntries(jvmti)));
boolean isConditionalConfigurationRun = !conditionalConfigUserPackageFilterFiles.isEmpty() || conditionalConfigPartialRun;
boolean shouldTraceOriginInformation = configurationWithOrigins || isConditionalConfigurationRun;
final MethodInfoRecordKeeper recordKeeper = new MethodInfoRecordKeeper(shouldTraceOriginInformation);
final Supplier<InterceptedState> interceptedStateSupplier = shouldTraceOriginInformation ? EagerlyLoadedJavaStackAccess.stackAccessSupplier()
: OnDemandJavaStackAccess.stackAccessSupplier();
if (configOutputDir != null) {
if (traceOutputFile != null) {
return usage("can only once specify exactly one of trace-output=, config-output-dir= or config-merge-dir=.");
}
try {
configOutputDirPath = Files.createDirectories(Path.of(configOutputDir));
configOutputLockFilePath = configOutputDirPath.resolve(ConfigurationFile.LOCK_FILE_NAME);
try {
Files.writeString(configOutputLockFilePath, Long.toString(ProcessProperties.getProcessID()),
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
} catch (FileAlreadyExistsException e) {
String process;
try {
process = Files.readString(configOutputLockFilePath).stripTrailing();
} catch (Exception ignored) {
process = "(unknown)";
}
return error(AGENT_ERROR, "Output directory '" + configOutputDirPath + "' is locked by process " + process + ", " +
"which means another agent instance is already writing to this directory. " +
"Only one agent instance can safely write to a specific target directory at the same time. " +
"Unless file '" + ConfigurationFile.LOCK_FILE_NAME + "' is a leftover from an earlier process that terminated abruptly, it is unsafe to delete it. " +
"For running multiple processes with agents at the same time to create a single configuration, read AutomaticMetadataCollection.md " +
"or https://www.graalvm.org/dev/reference-manual/native-image/metadata/AutomaticMetadataCollection/ on how to use the native-image-configure tool.");
}
if (experimentalOmitClasspathConfig) {
ignoreConfigFromClasspath(jvmti, omittedConfigs);
}
AccessAdvisor advisor = new AccessAdvisor(builtinHeuristicFilter, callerFilter, accessFilter, ignoredEntriesFile);
TraceProcessor processor = new TraceProcessor(advisor);
ConfigurationSet omittedConfiguration = new ConfigurationSet();
Predicate<String> shouldExcludeClassesWithHash = null;
if (!omittedConfigs.isEmpty()) {
Function<IOException, Exception> ignore = e -> {
warn("Failed to load omitted config: " + e);
return null;
};
omittedConfiguration = omittedConfigs.loadConfigurationSet(ignore, null, null);
shouldExcludeClassesWithHash = omittedConfiguration.getPredefinedClassesConfiguration()::containsClassWithHash;
}
if (shouldTraceOriginInformation) {
ConfigurationWithOriginsTracer configWithOriginsTracer = new ConfigurationWithOriginsTracer(processor, recordKeeper);
tracer = configWithOriginsTracer;
if (isConditionalConfigurationRun) {
if (conditionalConfigPartialRun) {
tracingResultWriter = new ConditionalConfigurationPartialRunWriter(configWithOriginsTracer);
} else {
ComplexFilter userCodeFilter = new ComplexFilter(HierarchyFilterNode.createRoot());
if (!parseFilterFiles(userCodeFilter, conditionalConfigUserPackageFilterFiles)) {
return PARSE_ERROR;
}
ComplexFilter classNameFilter;
if (!conditionalConfigClassNameFilterFiles.isEmpty()) {
classNameFilter = new ComplexFilter(HierarchyFilterNode.createRoot());
if (!parseFilterFiles(classNameFilter, conditionalConfigClassNameFilterFiles)) {
return PARSE_ERROR;
}
} else {
classNameFilter = new ComplexFilter(HierarchyFilterNode.createInclusiveRoot());
}
ConditionalConfigurationPredicate predicate = new ConditionalConfigurationPredicate(classNameFilter);
tracingResultWriter = new ConditionalConfigurationWriter(configWithOriginsTracer, userCodeFilter, predicate);
}
} else {
tracingResultWriter = new ConfigurationWithOriginsWriter(configWithOriginsTracer);
}
} else {
List<LazyValue<Path>> predefinedClassDestDirs = List.of(PredefinedClassesConfigurationParser.directorySupplier(configOutputDirPath));
Function<IOException, Exception> handler = e -> {
if (e instanceof NoSuchFileException) {
warn("file " + ((NoSuchFileException) e).getFile() + " for merging could not be found, skipping");
return null;
} else if (e instanceof FileNotFoundException) {
warn("could not open configuration file: " + e);
return null;
}
return e; // rethrow
};
ConfigurationSet configuration = mergeConfigs.loadConfigurationSet(handler, predefinedClassDestDirs, shouldExcludeClassesWithHash);
ConfigurationResultWriter writer = new ConfigurationResultWriter(processor, configuration, omittedConfiguration);
tracer = writer;
tracingResultWriter = writer;
}
expectedConfigModifiedBefore = getMostRecentlyModified(configOutputDirPath, getMostRecentlyModified(configOutputLockFilePath, null));
} catch (Throwable t) {
return error(AGENT_ERROR, t.toString());
}
} else {
try {
Path path = Paths.get(transformPath(traceOutputFile));
TraceFileWriter writer = new TraceFileWriter(path);
tracer = writer;
tracingResultWriter = writer;
} catch (Throwable t) {
return error(AGENT_ERROR, t.toString());
}
}
if (tracer != null) {
tracer.traceTrackReflectionMetadata(trackReflectionMetadata);
}
try {
BreakpointInterceptor.onLoad(jvmti, callbacks, tracer, this, interceptedStateSupplier,
experimentalClassLoaderSupport, experimentalClassDefineSupport, experimentalUnsafeAllocationSupport, trackReflectionMetadata);
} catch (Throwable t) {
return error(AGENT_ERROR, t.toString());
}
try {
JniCallInterceptor.onLoad(tracer, this, interceptedStateSupplier);
} catch (Throwable t) {
return error(AGENT_ERROR, t.toString());
}
setupExecutorServiceForPeriodicConfigurationCapture(configWritePeriod, configWritePeriodInitialDelay);
return SUCCESS;
}
private static void inform(String message) {
System.err.println(AGENT_NAME + ": " + message);
}
private static void warn(String message) {
// Checkstyle: Allow raw info or warning printing - begin
inform("Warning: " + message);
// Checkstyle: Allow raw info or warning printing - end
}
private static <T> T error(T result, String message) {
inform("Error: " + message);
return result;
}
private static int usage(String message) {
inform(message);
inform("Example usage: -agentlib:native-image-agent=config-output-dir=/path/to/config-dir/");
inform("For details, please read AutomaticMetadataCollection.md or https://www.graalvm.org/dev/reference-manual/native-image/metadata/AutomaticMetadataCollection/");
return USAGE_ERROR;
}
private static boolean checkJVMVersion(JvmtiEnv jvmti) {
String agentVersion = System.getProperty("java.vm.version");
int agentMajorVersion = Runtime.version().feature();
String vmVersion = Support.getSystemProperty(jvmti, "java.vm.version");
if (vmVersion == null) {
warn(String.format("Unable to determine the \"java.vm.version\" of the running JVM. Note that the JVM should have major version %d, otherwise metadata may be incorrect.",
agentMajorVersion));
return true;
}
// Fail if the major versions differ.
String[] parts = vmVersion.split("\\D");
if (parts.length == 0 || Integer.parseInt(parts[0]) != agentMajorVersion) {
return error(false, String.format(
"The current VM (%s) is incompatible with the agent, which was built for a JVM with major version %d. To resolve this issue, run the agent using a JVM with major version %d.",
vmVersion, agentMajorVersion, agentMajorVersion));
}
// Warn if the VM is different.
if (!vmVersion.startsWith(agentVersion)) {
warn(String.format(
"The running JVM (%s) is different from the JVM used to build the agent (%s). If the generated metadata is incorrect or incomplete, consider running the agent using the same JVM that built it.",
vmVersion, agentVersion));
}
return true;
}
private static int parseIntegerOrNegative(String number) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException ex) {
return -1;
}
}
private static boolean parseFilterFiles(ComplexFilter filter, List<String> filterFiles) {
for (String path : filterFiles) {
try {
new FilterConfigurationParser(filter).parseAndRegister(Paths.get(path).toUri());
} catch (Exception e) {
return error(false, "cannot parse filter file " + path + ": " + e);
}
}
filter.getHierarchyFilterNode().removeRedundantNodes();
return true;
}
private void setupExecutorServiceForPeriodicConfigurationCapture(int writePeriod, int initialDelay) {
if (tracingResultWriter == null || configOutputDirPath == null || !tracingResultWriter.supportsPeriodicTraceWriting()) {
return;
}
// No periodic writing of files by default
if (writePeriod == -1) {
return;
}
periodicConfigWriterExecutor = new ScheduledThreadPoolExecutor(1, r -> {
Thread workerThread = new Thread(r);
workerThread.setDaemon(true);
workerThread.setName("AgentConfigurationsPeriodicWriter");
return workerThread;
});
periodicConfigWriterExecutor.setRemoveOnCancelPolicy(true);
periodicConfigWriterExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
periodicConfigWriterExecutor.scheduleAtFixedRate(this::writeConfigurationFiles,
initialDelay, writePeriod, TimeUnit.SECONDS);
}
private static String[] getClasspathEntries(JvmtiEnv jvmti) {
String classpath = Support.getSystemProperty(jvmti, "java.class.path");
String sep = Support.getSystemProperty(jvmti, "path.separator");
if (sep == null) {
if (Platform.includedIn(Platform.LINUX.class) || Platform.includedIn(Platform.DARWIN.class)) {
sep = ":";
} else if (Platform.includedIn(Platform.WINDOWS.class)) {
sep = "[:;]";
} else {
warn("Running on unknown platform. Could not process classpath.");
return new String[]{};
}
}
String[] entries = classpath.split(sep);
for (int i = 0; i < entries.length; i++) {
try {
entries[i] = new File(entries[i]).getCanonicalPath();
} catch (IOException ex) {
warn("Could not normalize classpath entry %s. Agent output may be incorrect.".formatted(entries[i]));
}
}
return entries;
}
private static void ignoreConfigFromClasspath(JvmtiEnv jvmti, ConfigurationFileCollection ignoredConfigCollection) {
String[] entries = getClasspathEntries(jvmti);
AgentMetaInfProcessor processor = new AgentMetaInfProcessor(ignoredConfigCollection);
for (String cpEntry : entries) {
try {
NativeImageMetaInfWalker.walkMetaInfForCPEntry(Paths.get(cpEntry), processor);
} catch (NativeImageMetaInfWalker.MetaInfWalkException e) {
warn("Failed to walk the classpath entry: " + cpEntry + " Reason: " + e);
}
}
}
private static String transformPath(String path) {
String result = path;
if (result.contains("{pid}")) {
result = result.replace("{pid}", Long.toString(ProcessProperties.getProcessID()));
}
if (result.contains("{datetime}")) {
DateFormat fmt = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
fmt.setTimeZone(UTC_TIMEZONE);
result = result.replace("{datetime}", fmt.format(new Date()));
}
return result;
}
@Override
protected void onVMInitCallback(JvmtiEnv jvmti, JNIEnvironment jni, JNIObjectHandle thread) {
BreakpointInterceptor.onVMInit(jvmti, jni);
if (tracer != null) {
tracer.tracePhaseChange("live");
}
}
@Override
protected void onVMStartCallback(JvmtiEnv jvmti, JNIEnvironment jni) {
JniCallInterceptor.onVMStart(jvmti);
if (tracer != null) {
tracer.tracePhaseChange("start");
}
}
@Override
protected void onVMDeathCallback(JvmtiEnv jvmti, JNIEnvironment jni) {
if (tracer != null) {
tracer.tracePhaseChange("dead");
}
}
private static final int MAX_WARNINGS_FOR_WRITING_CONFIGS_FAILURES = 5;
private static int currentFailuresWritingConfigs = 0;
private static int currentFailuresModifiedTargetDirectory = 0;
private void writeConfigurationFiles() {
Path tempDirectory = null;
try {
FileTime mostRecent = getMostRecentlyModified(configOutputDirPath, expectedConfigModifiedBefore);
// Write files first before failing any modification checks
tempDirectory = Files.createTempDirectory(configOutputDirPath, transformPath("agent-pid{pid}-{datetime}.tmp"));
List<Path> tempFilePaths = tracingResultWriter.writeToDirectory(tempDirectory);
if (!Files.exists(configOutputLockFilePath)) {
throw unexpectedlyModified(configOutputLockFilePath);
}
expectUnmodified(configOutputLockFilePath);
/*
* Checking for the modification of the whole configuration directory is not possible
* since predefined classes configuration outputs folders and files during the agent
* run.
*/
Path[] targetFilePaths = new Path[tempFilePaths.size()];
for (int i = 0; i < tempFilePaths.size(); i++) {
Path fileName = tempDirectory.relativize(tempFilePaths.get(i));
targetFilePaths[i] = configOutputDirPath.resolve(fileName);
expectUnmodified(targetFilePaths[i]);
}
for (int i = 0; i < tempFilePaths.size(); i++) {
tryAtomicMove(tempFilePaths.get(i), targetFilePaths[i]);
mostRecent = getMostRecentlyModified(targetFilePaths[i], mostRecent);
}
mostRecent = getMostRecentlyModified(configOutputDirPath, mostRecent);
expectedConfigModifiedBefore = mostRecent;
/*
* Note that sidecar files may be written directly to the final output directory, such
* as the class files from predefined class tracking. However, such files generally
* don't change once they have been written.
*/
compulsoryDelete(tempDirectory);
} catch (IOException e) {
warnUpToLimit(currentFailuresWritingConfigs++, MAX_WARNINGS_FOR_WRITING_CONFIGS_FAILURES, "Error when writing configuration files: " + e);
} catch (ConcurrentModificationException e) {
warnUpToLimit(currentFailuresModifiedTargetDirectory++, MAX_WARNINGS_FOR_WRITING_CONFIGS_FAILURES,
"file or directory '" + e.getMessage() + "' has been modified by another process. " +
"All output files remain in the temporary directory '" + configOutputDirPath.resolve("..").relativize(tempDirectory) + "'. " +
"Ensure that only one agent instance and no other processes are writing to the output directory '" + configOutputDirPath + "' at the same time. " +
"For running multiple processes with agents at the same time to create a single configuration, read AutomaticMetadataCollection.md " +
"or https://www.graalvm.org/dev/reference-manual/native-image/metadata/AutomaticMetadataCollection/ on how to use the native-image-configure tool.");
}
}
private void expectUnmodified(Path path) {
try {
if (Files.getLastModifiedTime(path).compareTo(expectedConfigModifiedBefore) > 0) {
throw unexpectedlyModified(path);
}
} catch (IOException ignored) {
// best effort
}
}
private static ConcurrentModificationException unexpectedlyModified(Path path) {
throw new ConcurrentModificationException(path.getFileName().toString());
}
private static FileTime getMostRecentlyModified(Path path, FileTime other) {
FileTime modified;
try {
modified = Files.getLastModifiedTime(path);
} catch (IOException ignored) {
return other; // best effort
}
return (other == null || other.compareTo(modified) < 0) ? modified : other;
}
@SuppressWarnings("BusyWait")
private static void compulsoryDelete(Path pathToDelete) {
final int maxRetries = 3;
int retries = 0;
while (pathToDelete.toFile().exists() && !pathToDelete.toFile().delete() && retries < maxRetries) {
try {
Thread.sleep((long) (100 + Math.random() * 500));
} catch (InterruptedException e) {
}
retries++;
}
}
private static void warnUpToLimit(int currentCount, int limit, String message) {
if (currentCount < limit) {
warn(message);
return;
}
if (currentCount == limit) {
warn(message);
warn("The above warning will no longer be reported.");
}
}
private static final int MAX_FAILURES_ATOMIC_MOVE = 20;
private static int currentFailuresAtomicMove = 0;
private static void tryAtomicMove(final Path source, final Path target) throws IOException {
try {
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
warnUpToLimit(currentFailuresAtomicMove++, MAX_FAILURES_ATOMIC_MOVE,
String.format("Could not move temporary configuration profile from '%s' to '%s' atomically. " +
"This might result in inconsistencies.", source.toAbsolutePath(), target.toAbsolutePath()));
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
}
}
@Override
protected int onUnloadCallback(JNIJavaVM vm) {
if (periodicConfigWriterExecutor != null) {
periodicConfigWriterExecutor.shutdown();
try {
periodicConfigWriterExecutor.awaitTermination(300, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
periodicConfigWriterExecutor.shutdownNow();
}
}
if (tracer != null) {
tracer.tracePhaseChange("unload");
}
if (tracingResultWriter != null) {
tracingResultWriter.close();
if (tracingResultWriter.supportsOnUnloadTraceWriting()) {
if (configOutputDirPath != null) {
writeConfigurationFiles();
compulsoryDelete(configOutputLockFilePath);
configOutputLockFilePath = null;
configOutputDirPath = null;
}
}
}
/*
* Agent shutdown is tricky: apparently we can still have events at the same time as this
* function executes, so we would need to synchronize. We could do this with a combined
* shared+exclusive lock, but that adds some cost to all events. We choose to leak a few
* handles and some memory for now -- this agent isn't supposed to be attached only
* temporarily anyway, and the impending process exit should free any resources we take
* (unless another JVM is launched in this process).
*/
// cleanupOnUnload(vm);
/*
* The epilogue of this method does not tear down our VM: we don't seem to observe all
* threads that end and therefore can't detach them, so we would wait forever for them.
*/
return SUCCESS;
}
static class ExitCodes {
static final int SUCCESS = 0;
static final int USAGE_ERROR = 1;
static final int PARSE_ERROR = 2;
static final int AGENT_ERROR = 3;
}
@SuppressWarnings("unused")
private static void cleanupOnUnload(JNIJavaVM vm) {
JniCallInterceptor.onUnload();
BreakpointInterceptor.onUnload();
}
@SuppressWarnings("unused")
public static class RegistrationFeature implements Feature {
@Override
public void afterRegistration(AfterRegistrationAccess access) {
JvmtiAgentBase.registerAgent(new NativeImageAgent());
}
}
}
|
googleapis/sdk-platform-java | 38,039 | java-iam/proto-google-iam-v2/src/main/java/com/google/iam/v2/CreatePolicyRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/iam/v2/policy.proto
// Protobuf Java Version: 3.25.8
package com.google.iam.v2;
/**
*
*
* <pre>
* Request message for `CreatePolicy`.
* </pre>
*
* Protobuf type {@code google.iam.v2.CreatePolicyRequest}
*/
public final class CreatePolicyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.iam.v2.CreatePolicyRequest)
CreatePolicyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreatePolicyRequest.newBuilder() to construct.
private CreatePolicyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreatePolicyRequest() {
parent_ = "";
policyId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreatePolicyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.iam.v2.PolicyProto
.internal_static_google_iam_v2_CreatePolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.iam.v2.PolicyProto
.internal_static_google_iam_v2_CreatePolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.iam.v2.CreatePolicyRequest.class,
com.google.iam.v2.CreatePolicyRequest.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 that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int POLICY_FIELD_NUMBER = 2;
private com.google.iam.v2.Policy policy_;
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the policy field is set.
*/
@java.lang.Override
public boolean hasPolicy() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The policy.
*/
@java.lang.Override
public com.google.iam.v2.Policy getPolicy() {
return policy_ == null ? com.google.iam.v2.Policy.getDefaultInstance() : policy_;
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.iam.v2.PolicyOrBuilder getPolicyOrBuilder() {
return policy_ == null ? com.google.iam.v2.Policy.getDefaultInstance() : policy_;
}
public static final int POLICY_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object policyId_ = "";
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @return The policyId.
*/
@java.lang.Override
public java.lang.String getPolicyId() {
java.lang.Object ref = policyId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
policyId_ = s;
return s;
}
}
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @return The bytes for policyId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPolicyIdBytes() {
java.lang.Object ref = policyId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
policyId_ = 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, getPolicy());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(policyId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, policyId_);
}
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, getPolicy());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(policyId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, policyId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.iam.v2.CreatePolicyRequest)) {
return super.equals(obj);
}
com.google.iam.v2.CreatePolicyRequest other = (com.google.iam.v2.CreatePolicyRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasPolicy() != other.hasPolicy()) return false;
if (hasPolicy()) {
if (!getPolicy().equals(other.getPolicy())) return false;
}
if (!getPolicyId().equals(other.getPolicyId())) 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 (hasPolicy()) {
hash = (37 * hash) + POLICY_FIELD_NUMBER;
hash = (53 * hash) + getPolicy().hashCode();
}
hash = (37 * hash) + POLICY_ID_FIELD_NUMBER;
hash = (53 * hash) + getPolicyId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.iam.v2.CreatePolicyRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.iam.v2.CreatePolicyRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.iam.v2.CreatePolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.iam.v2.CreatePolicyRequest 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 `CreatePolicy`.
* </pre>
*
* Protobuf type {@code google.iam.v2.CreatePolicyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.iam.v2.CreatePolicyRequest)
com.google.iam.v2.CreatePolicyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.iam.v2.PolicyProto
.internal_static_google_iam_v2_CreatePolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.iam.v2.PolicyProto
.internal_static_google_iam_v2_CreatePolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.iam.v2.CreatePolicyRequest.class,
com.google.iam.v2.CreatePolicyRequest.Builder.class);
}
// Construct using com.google.iam.v2.CreatePolicyRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPolicyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
policy_ = null;
if (policyBuilder_ != null) {
policyBuilder_.dispose();
policyBuilder_ = null;
}
policyId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.iam.v2.PolicyProto
.internal_static_google_iam_v2_CreatePolicyRequest_descriptor;
}
@java.lang.Override
public com.google.iam.v2.CreatePolicyRequest getDefaultInstanceForType() {
return com.google.iam.v2.CreatePolicyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.iam.v2.CreatePolicyRequest build() {
com.google.iam.v2.CreatePolicyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.iam.v2.CreatePolicyRequest buildPartial() {
com.google.iam.v2.CreatePolicyRequest result =
new com.google.iam.v2.CreatePolicyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.iam.v2.CreatePolicyRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.policy_ = policyBuilder_ == null ? policy_ : policyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.policyId_ = policyId_;
}
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.iam.v2.CreatePolicyRequest) {
return mergeFrom((com.google.iam.v2.CreatePolicyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.iam.v2.CreatePolicyRequest other) {
if (other == com.google.iam.v2.CreatePolicyRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasPolicy()) {
mergePolicy(other.getPolicy());
}
if (!other.getPolicyId().isEmpty()) {
policyId_ = other.policyId_;
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(getPolicyFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
policyId_ = 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 resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource that the policy is attached to, along with the kind of policy
* to create. Format: `policies/{attachment_point}/denypolicies`
*
*
* The attachment point is identified by its URL-encoded full resource name,
* which means that the forward-slash character, `/`, must be written as
* `%2F`. For example,
* `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`.
*
* For organizations and folders, use the numeric ID in the full resource
* name. For projects, you can use the alphanumeric or the numeric ID.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.iam.v2.Policy policy_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.iam.v2.Policy,
com.google.iam.v2.Policy.Builder,
com.google.iam.v2.PolicyOrBuilder>
policyBuilder_;
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the policy field is set.
*/
public boolean hasPolicy() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The policy.
*/
public com.google.iam.v2.Policy getPolicy() {
if (policyBuilder_ == null) {
return policy_ == null ? com.google.iam.v2.Policy.getDefaultInstance() : policy_;
} else {
return policyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setPolicy(com.google.iam.v2.Policy value) {
if (policyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
policy_ = value;
} else {
policyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setPolicy(com.google.iam.v2.Policy.Builder builderForValue) {
if (policyBuilder_ == null) {
policy_ = builderForValue.build();
} else {
policyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergePolicy(com.google.iam.v2.Policy value) {
if (policyBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& policy_ != null
&& policy_ != com.google.iam.v2.Policy.getDefaultInstance()) {
getPolicyBuilder().mergeFrom(value);
} else {
policy_ = value;
}
} else {
policyBuilder_.mergeFrom(value);
}
if (policy_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearPolicy() {
bitField0_ = (bitField0_ & ~0x00000002);
policy_ = null;
if (policyBuilder_ != null) {
policyBuilder_.dispose();
policyBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.iam.v2.Policy.Builder getPolicyBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getPolicyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.iam.v2.PolicyOrBuilder getPolicyOrBuilder() {
if (policyBuilder_ != null) {
return policyBuilder_.getMessageOrBuilder();
} else {
return policy_ == null ? com.google.iam.v2.Policy.getDefaultInstance() : policy_;
}
}
/**
*
*
* <pre>
* Required. The policy to create.
* </pre>
*
* <code>.google.iam.v2.Policy policy = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.iam.v2.Policy,
com.google.iam.v2.Policy.Builder,
com.google.iam.v2.PolicyOrBuilder>
getPolicyFieldBuilder() {
if (policyBuilder_ == null) {
policyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.iam.v2.Policy,
com.google.iam.v2.Policy.Builder,
com.google.iam.v2.PolicyOrBuilder>(getPolicy(), getParentForChildren(), isClean());
policy_ = null;
}
return policyBuilder_;
}
private java.lang.Object policyId_ = "";
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @return The policyId.
*/
public java.lang.String getPolicyId() {
java.lang.Object ref = policyId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
policyId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @return The bytes for policyId.
*/
public com.google.protobuf.ByteString getPolicyIdBytes() {
java.lang.Object ref = policyId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
policyId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @param value The policyId to set.
* @return This builder for chaining.
*/
public Builder setPolicyId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
policyId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPolicyId() {
policyId_ = getDefaultInstance().getPolicyId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The ID to use for this policy, which will become the final component of
* the policy's resource name. The ID must contain 3 to 63 characters. It can
* contain lowercase letters and numbers, as well as dashes (`-`) and periods
* (`.`). The first character must be a lowercase letter.
* </pre>
*
* <code>string policy_id = 3;</code>
*
* @param value The bytes for policyId to set.
* @return This builder for chaining.
*/
public Builder setPolicyIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
policyId_ = 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.iam.v2.CreatePolicyRequest)
}
// @@protoc_insertion_point(class_scope:google.iam.v2.CreatePolicyRequest)
private static final com.google.iam.v2.CreatePolicyRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.iam.v2.CreatePolicyRequest();
}
public static com.google.iam.v2.CreatePolicyRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreatePolicyRequest> PARSER =
new com.google.protobuf.AbstractParser<CreatePolicyRequest>() {
@java.lang.Override
public CreatePolicyRequest 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<CreatePolicyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreatePolicyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.iam.v2.CreatePolicyRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 37,983 | java-discoveryengine/proto-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/ListControlsRequest.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/v1beta/control_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1beta;
/**
*
*
* <pre>
* Request for ListControls method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.ListControlsRequest}
*/
public final class ListControlsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1beta.ListControlsRequest)
ListControlsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListControlsRequest.newBuilder() to construct.
private ListControlsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListControlsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListControlsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.ControlServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListControlsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.ControlServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListControlsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.ListControlsRequest.class,
com.google.cloud.discoveryengine.v1beta.ListControlsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. Maximum number of results to return. If unspecified, defaults
* to 50. Max allowed value is 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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1beta.ListControlsRequest)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1beta.ListControlsRequest other =
(com.google.cloud.discoveryengine.v1beta.ListControlsRequest) 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.discoveryengine.v1beta.ListControlsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.v1beta.ListControlsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.v1beta.ListControlsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.v1beta.ListControlsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.v1beta.ListControlsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.v1beta.ListControlsRequest 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 ListControls method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1beta.ListControlsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1beta.ListControlsRequest)
com.google.cloud.discoveryengine.v1beta.ListControlsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1beta.ControlServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListControlsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1beta.ControlServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListControlsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1beta.ListControlsRequest.class,
com.google.cloud.discoveryengine.v1beta.ListControlsRequest.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1beta.ListControlsRequest.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.discoveryengine.v1beta.ControlServiceProto
.internal_static_google_cloud_discoveryengine_v1beta_ListControlsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListControlsRequest getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1beta.ListControlsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListControlsRequest build() {
com.google.cloud.discoveryengine.v1beta.ListControlsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListControlsRequest buildPartial() {
com.google.cloud.discoveryengine.v1beta.ListControlsRequest result =
new com.google.cloud.discoveryengine.v1beta.ListControlsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.discoveryengine.v1beta.ListControlsRequest 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.discoveryengine.v1beta.ListControlsRequest) {
return mergeFrom((com.google.cloud.discoveryengine.v1beta.ListControlsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.discoveryengine.v1beta.ListControlsRequest other) {
if (other == com.google.cloud.discoveryengine.v1beta.ListControlsRequest.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 data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The data store resource name. Format:
* `projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}`
* or
* `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. Maximum number of results to return. If unspecified, defaults
* to 50. Max allowed value is 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. Maximum number of results to return. If unspecified, defaults
* to 50. Max allowed value is 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. Maximum number of results to return. If unspecified, defaults
* to 50. Max allowed value is 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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </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 page token, received from a previous `ListControls` call.
* Provide this to retrieve the subsequent page.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A filter to apply on the list results. Supported features:
*
* * List all the products under the parent branch if
* [filter][google.cloud.discoveryengine.v1beta.ListControlsRequest.filter] is
* unset. Currently this field is unsupported.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1beta.ListControlsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1beta.ListControlsRequest)
private static final com.google.cloud.discoveryengine.v1beta.ListControlsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1beta.ListControlsRequest();
}
public static com.google.cloud.discoveryengine.v1beta.ListControlsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListControlsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListControlsRequest>() {
@java.lang.Override
public ListControlsRequest 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<ListControlsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListControlsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1beta.ListControlsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 37,986 | clients/google-api-services-admin/directory_v1/1.31.0/com/google/api/services/directory/model/MobileDevice.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.directory.model;
/**
* Google Workspace Mobile Management includes Android, [Google
* Sync](https://support.google.com/a/answer/135937), and iOS devices. For more information about
* common group mobile device API tasks, see the [Developer's Guide](/admin-sdk/directory/v1/guides
* /manage-mobile-devices.html).
*
* <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 Admin SDK 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 MobileDevice extends com.google.api.client.json.GenericJson {
/**
* Adb (USB debugging) enabled or disabled on device (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adbStatus;
/**
* The list of applications installed on an Android mobile device. It is not applicable to Google
* Sync and iOS devices. The list includes any Android applications that access Google Workspace
* data. When updating an applications list, it is important to note that updates replace the
* existing list. If the Android device has two existing applications and the API updates the list
* with five applications, the is now the updated list of five applications.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Applications> applications;
static {
// hack to force ProGuard to consider Applications 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(Applications.class);
}
/**
* The device's baseband version.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String basebandVersion;
/**
* Mobile Device Bootloader version (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String bootloaderVersion;
/**
* Mobile Device Brand (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String brand;
/**
* The device's operating system build number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String buildNumber;
/**
* The default locale used on the device.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String defaultLanguage;
/**
* Developer options enabled or disabled on device (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean developerOptionsStatus;
/**
* The compromised device status.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String deviceCompromisedStatus;
/**
* The serial number for a Google Sync mobile device. For Android and iOS devices, this is a
* software generated unique identifier.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String deviceId;
/**
* DevicePasswordStatus (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String devicePasswordStatus;
/**
* List of owner's email addresses. If your application needs the current list of user emails, use
* the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For additional
* information, see the [retrieve a user](/admin-sdk/directory/v1/guides/manage-users#get_user)
* method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> email;
/**
* Mobile Device Encryption Status (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String encryptionStatus;
/**
* ETag of the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String etag;
/**
* Date and time the device was first synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime firstSync;
/**
* Mobile Device Hardware (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String hardware;
/**
* The IMEI/MEID unique identifier for Android hardware. It is not applicable to Google Sync
* devices. When adding an Android mobile device, this is an optional property. When updating one
* of these devices, this is a read-only property.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String hardwareId;
/**
* The device's IMEI number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String imei;
/**
* The device's kernel version.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kernelVersion;
/**
* The type of the API resource. For Mobiledevices resources, the value is
* `admin#directory#mobiledevice`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Date and time the device was last synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime lastSync;
/**
* Boolean indicating if this account is on owner/primary profile or not.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean managedAccountIsOnOwnerProfile;
/**
* Mobile Device manufacturer (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String manufacturer;
/**
* The device's MEID number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String meid;
/**
* The mobile device's model name, for example Nexus S. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile=devices#update_mobile_device).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String model;
/**
* List of the owner's user names. If your application needs the current list of device owner
* names, use the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For more
* information about retrieving mobile device user information, see the [Developer's Guide
* ](/admin-sdk/directory/v1/guides/manage-users#get_user).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> name;
/**
* Mobile Device mobile or network operator (if available) (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String networkOperator;
/**
* The mobile device's operating system, for example IOS 4.3 or Android 2.3.5. This property can
* be [updated](/admin-sdk/directory/v1/reference/mobiledevices/update.html). For more
* information, see the [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-
* devices#update_mobile_device).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String os;
/**
* List of accounts added on device (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> otherAccountsInfo;
/**
* DMAgentPermission (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String privilege;
/**
* Mobile Device release version version (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String releaseVersion;
/**
* The unique ID the API service uses to identify the mobile device.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String resourceId;
/**
* Mobile Device Security patch level (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long securityPatchLevel;
/**
* The device's serial number.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String serialNumber;
/**
* The device's status.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Work profile supported on device (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean supportsWorkProfile;
/**
* The type of mobile device.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Unknown sources enabled or disabled on device (Read-only)
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean unknownSourcesStatus;
/**
* Gives information about the device such as `os` version. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-devices#update_mobile_device).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String userAgent;
/**
* The device's MAC address on Wi-Fi networks.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String wifiMacAddress;
/**
* Adb (USB debugging) enabled or disabled on device (Read-only)
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdbStatus() {
return adbStatus;
}
/**
* Adb (USB debugging) enabled or disabled on device (Read-only)
* @param adbStatus adbStatus or {@code null} for none
*/
public MobileDevice setAdbStatus(java.lang.Boolean adbStatus) {
this.adbStatus = adbStatus;
return this;
}
/**
* The list of applications installed on an Android mobile device. It is not applicable to Google
* Sync and iOS devices. The list includes any Android applications that access Google Workspace
* data. When updating an applications list, it is important to note that updates replace the
* existing list. If the Android device has two existing applications and the API updates the list
* with five applications, the is now the updated list of five applications.
* @return value or {@code null} for none
*/
public java.util.List<Applications> getApplications() {
return applications;
}
/**
* The list of applications installed on an Android mobile device. It is not applicable to Google
* Sync and iOS devices. The list includes any Android applications that access Google Workspace
* data. When updating an applications list, it is important to note that updates replace the
* existing list. If the Android device has two existing applications and the API updates the list
* with five applications, the is now the updated list of five applications.
* @param applications applications or {@code null} for none
*/
public MobileDevice setApplications(java.util.List<Applications> applications) {
this.applications = applications;
return this;
}
/**
* The device's baseband version.
* @return value or {@code null} for none
*/
public java.lang.String getBasebandVersion() {
return basebandVersion;
}
/**
* The device's baseband version.
* @param basebandVersion basebandVersion or {@code null} for none
*/
public MobileDevice setBasebandVersion(java.lang.String basebandVersion) {
this.basebandVersion = basebandVersion;
return this;
}
/**
* Mobile Device Bootloader version (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getBootloaderVersion() {
return bootloaderVersion;
}
/**
* Mobile Device Bootloader version (Read-only)
* @param bootloaderVersion bootloaderVersion or {@code null} for none
*/
public MobileDevice setBootloaderVersion(java.lang.String bootloaderVersion) {
this.bootloaderVersion = bootloaderVersion;
return this;
}
/**
* Mobile Device Brand (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getBrand() {
return brand;
}
/**
* Mobile Device Brand (Read-only)
* @param brand brand or {@code null} for none
*/
public MobileDevice setBrand(java.lang.String brand) {
this.brand = brand;
return this;
}
/**
* The device's operating system build number.
* @return value or {@code null} for none
*/
public java.lang.String getBuildNumber() {
return buildNumber;
}
/**
* The device's operating system build number.
* @param buildNumber buildNumber or {@code null} for none
*/
public MobileDevice setBuildNumber(java.lang.String buildNumber) {
this.buildNumber = buildNumber;
return this;
}
/**
* The default locale used on the device.
* @return value or {@code null} for none
*/
public java.lang.String getDefaultLanguage() {
return defaultLanguage;
}
/**
* The default locale used on the device.
* @param defaultLanguage defaultLanguage or {@code null} for none
*/
public MobileDevice setDefaultLanguage(java.lang.String defaultLanguage) {
this.defaultLanguage = defaultLanguage;
return this;
}
/**
* Developer options enabled or disabled on device (Read-only)
* @return value or {@code null} for none
*/
public java.lang.Boolean getDeveloperOptionsStatus() {
return developerOptionsStatus;
}
/**
* Developer options enabled or disabled on device (Read-only)
* @param developerOptionsStatus developerOptionsStatus or {@code null} for none
*/
public MobileDevice setDeveloperOptionsStatus(java.lang.Boolean developerOptionsStatus) {
this.developerOptionsStatus = developerOptionsStatus;
return this;
}
/**
* The compromised device status.
* @return value or {@code null} for none
*/
public java.lang.String getDeviceCompromisedStatus() {
return deviceCompromisedStatus;
}
/**
* The compromised device status.
* @param deviceCompromisedStatus deviceCompromisedStatus or {@code null} for none
*/
public MobileDevice setDeviceCompromisedStatus(java.lang.String deviceCompromisedStatus) {
this.deviceCompromisedStatus = deviceCompromisedStatus;
return this;
}
/**
* The serial number for a Google Sync mobile device. For Android and iOS devices, this is a
* software generated unique identifier.
* @return value or {@code null} for none
*/
public java.lang.String getDeviceId() {
return deviceId;
}
/**
* The serial number for a Google Sync mobile device. For Android and iOS devices, this is a
* software generated unique identifier.
* @param deviceId deviceId or {@code null} for none
*/
public MobileDevice setDeviceId(java.lang.String deviceId) {
this.deviceId = deviceId;
return this;
}
/**
* DevicePasswordStatus (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getDevicePasswordStatus() {
return devicePasswordStatus;
}
/**
* DevicePasswordStatus (Read-only)
* @param devicePasswordStatus devicePasswordStatus or {@code null} for none
*/
public MobileDevice setDevicePasswordStatus(java.lang.String devicePasswordStatus) {
this.devicePasswordStatus = devicePasswordStatus;
return this;
}
/**
* List of owner's email addresses. If your application needs the current list of user emails, use
* the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For additional
* information, see the [retrieve a user](/admin-sdk/directory/v1/guides/manage-users#get_user)
* method.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getEmail() {
return email;
}
/**
* List of owner's email addresses. If your application needs the current list of user emails, use
* the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For additional
* information, see the [retrieve a user](/admin-sdk/directory/v1/guides/manage-users#get_user)
* method.
* @param email email or {@code null} for none
*/
public MobileDevice setEmail(java.util.List<java.lang.String> email) {
this.email = email;
return this;
}
/**
* Mobile Device Encryption Status (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getEncryptionStatus() {
return encryptionStatus;
}
/**
* Mobile Device Encryption Status (Read-only)
* @param encryptionStatus encryptionStatus or {@code null} for none
*/
public MobileDevice setEncryptionStatus(java.lang.String encryptionStatus) {
this.encryptionStatus = encryptionStatus;
return this;
}
/**
* ETag of the resource.
* @return value or {@code null} for none
*/
public java.lang.String getEtag() {
return etag;
}
/**
* ETag of the resource.
* @param etag etag or {@code null} for none
*/
public MobileDevice setEtag(java.lang.String etag) {
this.etag = etag;
return this;
}
/**
* Date and time the device was first synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getFirstSync() {
return firstSync;
}
/**
* Date and time the device was first synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* @param firstSync firstSync or {@code null} for none
*/
public MobileDevice setFirstSync(com.google.api.client.util.DateTime firstSync) {
this.firstSync = firstSync;
return this;
}
/**
* Mobile Device Hardware (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getHardware() {
return hardware;
}
/**
* Mobile Device Hardware (Read-only)
* @param hardware hardware or {@code null} for none
*/
public MobileDevice setHardware(java.lang.String hardware) {
this.hardware = hardware;
return this;
}
/**
* The IMEI/MEID unique identifier for Android hardware. It is not applicable to Google Sync
* devices. When adding an Android mobile device, this is an optional property. When updating one
* of these devices, this is a read-only property.
* @return value or {@code null} for none
*/
public java.lang.String getHardwareId() {
return hardwareId;
}
/**
* The IMEI/MEID unique identifier for Android hardware. It is not applicable to Google Sync
* devices. When adding an Android mobile device, this is an optional property. When updating one
* of these devices, this is a read-only property.
* @param hardwareId hardwareId or {@code null} for none
*/
public MobileDevice setHardwareId(java.lang.String hardwareId) {
this.hardwareId = hardwareId;
return this;
}
/**
* The device's IMEI number.
* @return value or {@code null} for none
*/
public java.lang.String getImei() {
return imei;
}
/**
* The device's IMEI number.
* @param imei imei or {@code null} for none
*/
public MobileDevice setImei(java.lang.String imei) {
this.imei = imei;
return this;
}
/**
* The device's kernel version.
* @return value or {@code null} for none
*/
public java.lang.String getKernelVersion() {
return kernelVersion;
}
/**
* The device's kernel version.
* @param kernelVersion kernelVersion or {@code null} for none
*/
public MobileDevice setKernelVersion(java.lang.String kernelVersion) {
this.kernelVersion = kernelVersion;
return this;
}
/**
* The type of the API resource. For Mobiledevices resources, the value is
* `admin#directory#mobiledevice`.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* The type of the API resource. For Mobiledevices resources, the value is
* `admin#directory#mobiledevice`.
* @param kind kind or {@code null} for none
*/
public MobileDevice setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Date and time the device was last synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getLastSync() {
return lastSync;
}
/**
* Date and time the device was last synchronized with the policy settings in the G Suite
* administrator control panel (Read-only)
* @param lastSync lastSync or {@code null} for none
*/
public MobileDevice setLastSync(com.google.api.client.util.DateTime lastSync) {
this.lastSync = lastSync;
return this;
}
/**
* Boolean indicating if this account is on owner/primary profile or not.
* @return value or {@code null} for none
*/
public java.lang.Boolean getManagedAccountIsOnOwnerProfile() {
return managedAccountIsOnOwnerProfile;
}
/**
* Boolean indicating if this account is on owner/primary profile or not.
* @param managedAccountIsOnOwnerProfile managedAccountIsOnOwnerProfile or {@code null} for none
*/
public MobileDevice setManagedAccountIsOnOwnerProfile(java.lang.Boolean managedAccountIsOnOwnerProfile) {
this.managedAccountIsOnOwnerProfile = managedAccountIsOnOwnerProfile;
return this;
}
/**
* Mobile Device manufacturer (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getManufacturer() {
return manufacturer;
}
/**
* Mobile Device manufacturer (Read-only)
* @param manufacturer manufacturer or {@code null} for none
*/
public MobileDevice setManufacturer(java.lang.String manufacturer) {
this.manufacturer = manufacturer;
return this;
}
/**
* The device's MEID number.
* @return value or {@code null} for none
*/
public java.lang.String getMeid() {
return meid;
}
/**
* The device's MEID number.
* @param meid meid or {@code null} for none
*/
public MobileDevice setMeid(java.lang.String meid) {
this.meid = meid;
return this;
}
/**
* The mobile device's model name, for example Nexus S. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile=devices#update_mobile_device).
* @return value or {@code null} for none
*/
public java.lang.String getModel() {
return model;
}
/**
* The mobile device's model name, for example Nexus S. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile=devices#update_mobile_device).
* @param model model or {@code null} for none
*/
public MobileDevice setModel(java.lang.String model) {
this.model = model;
return this;
}
/**
* List of the owner's user names. If your application needs the current list of device owner
* names, use the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For more
* information about retrieving mobile device user information, see the [Developer's Guide
* ](/admin-sdk/directory/v1/guides/manage-users#get_user).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getName() {
return name;
}
/**
* List of the owner's user names. If your application needs the current list of device owner
* names, use the [get](/admin-sdk/directory/v1/reference/mobiledevices/get.html) method. For more
* information about retrieving mobile device user information, see the [Developer's Guide
* ](/admin-sdk/directory/v1/guides/manage-users#get_user).
* @param name name or {@code null} for none
*/
public MobileDevice setName(java.util.List<java.lang.String> name) {
this.name = name;
return this;
}
/**
* Mobile Device mobile or network operator (if available) (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getNetworkOperator() {
return networkOperator;
}
/**
* Mobile Device mobile or network operator (if available) (Read-only)
* @param networkOperator networkOperator or {@code null} for none
*/
public MobileDevice setNetworkOperator(java.lang.String networkOperator) {
this.networkOperator = networkOperator;
return this;
}
/**
* The mobile device's operating system, for example IOS 4.3 or Android 2.3.5. This property can
* be [updated](/admin-sdk/directory/v1/reference/mobiledevices/update.html). For more
* information, see the [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-
* devices#update_mobile_device).
* @return value or {@code null} for none
*/
public java.lang.String getOs() {
return os;
}
/**
* The mobile device's operating system, for example IOS 4.3 or Android 2.3.5. This property can
* be [updated](/admin-sdk/directory/v1/reference/mobiledevices/update.html). For more
* information, see the [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-
* devices#update_mobile_device).
* @param os os or {@code null} for none
*/
public MobileDevice setOs(java.lang.String os) {
this.os = os;
return this;
}
/**
* List of accounts added on device (Read-only)
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getOtherAccountsInfo() {
return otherAccountsInfo;
}
/**
* List of accounts added on device (Read-only)
* @param otherAccountsInfo otherAccountsInfo or {@code null} for none
*/
public MobileDevice setOtherAccountsInfo(java.util.List<java.lang.String> otherAccountsInfo) {
this.otherAccountsInfo = otherAccountsInfo;
return this;
}
/**
* DMAgentPermission (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getPrivilege() {
return privilege;
}
/**
* DMAgentPermission (Read-only)
* @param privilege privilege or {@code null} for none
*/
public MobileDevice setPrivilege(java.lang.String privilege) {
this.privilege = privilege;
return this;
}
/**
* Mobile Device release version version (Read-only)
* @return value or {@code null} for none
*/
public java.lang.String getReleaseVersion() {
return releaseVersion;
}
/**
* Mobile Device release version version (Read-only)
* @param releaseVersion releaseVersion or {@code null} for none
*/
public MobileDevice setReleaseVersion(java.lang.String releaseVersion) {
this.releaseVersion = releaseVersion;
return this;
}
/**
* The unique ID the API service uses to identify the mobile device.
* @return value or {@code null} for none
*/
public java.lang.String getResourceId() {
return resourceId;
}
/**
* The unique ID the API service uses to identify the mobile device.
* @param resourceId resourceId or {@code null} for none
*/
public MobileDevice setResourceId(java.lang.String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* Mobile Device Security patch level (Read-only)
* @return value or {@code null} for none
*/
public java.lang.Long getSecurityPatchLevel() {
return securityPatchLevel;
}
/**
* Mobile Device Security patch level (Read-only)
* @param securityPatchLevel securityPatchLevel or {@code null} for none
*/
public MobileDevice setSecurityPatchLevel(java.lang.Long securityPatchLevel) {
this.securityPatchLevel = securityPatchLevel;
return this;
}
/**
* The device's serial number.
* @return value or {@code null} for none
*/
public java.lang.String getSerialNumber() {
return serialNumber;
}
/**
* The device's serial number.
* @param serialNumber serialNumber or {@code null} for none
*/
public MobileDevice setSerialNumber(java.lang.String serialNumber) {
this.serialNumber = serialNumber;
return this;
}
/**
* The device's status.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* The device's status.
* @param status status or {@code null} for none
*/
public MobileDevice setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Work profile supported on device (Read-only)
* @return value or {@code null} for none
*/
public java.lang.Boolean getSupportsWorkProfile() {
return supportsWorkProfile;
}
/**
* Work profile supported on device (Read-only)
* @param supportsWorkProfile supportsWorkProfile or {@code null} for none
*/
public MobileDevice setSupportsWorkProfile(java.lang.Boolean supportsWorkProfile) {
this.supportsWorkProfile = supportsWorkProfile;
return this;
}
/**
* The type of mobile device.
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* The type of mobile device.
* @param type type or {@code null} for none
*/
public MobileDevice setType(java.lang.String type) {
this.type = type;
return this;
}
/**
* Unknown sources enabled or disabled on device (Read-only)
* @return value or {@code null} for none
*/
public java.lang.Boolean getUnknownSourcesStatus() {
return unknownSourcesStatus;
}
/**
* Unknown sources enabled or disabled on device (Read-only)
* @param unknownSourcesStatus unknownSourcesStatus or {@code null} for none
*/
public MobileDevice setUnknownSourcesStatus(java.lang.Boolean unknownSourcesStatus) {
this.unknownSourcesStatus = unknownSourcesStatus;
return this;
}
/**
* Gives information about the device such as `os` version. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-devices#update_mobile_device).
* @return value or {@code null} for none
*/
public java.lang.String getUserAgent() {
return userAgent;
}
/**
* Gives information about the device such as `os` version. This property can be [updated](/admin-
* sdk/directory/v1/reference/mobiledevices/update.html). For more information, see the
* [Developer's Guide](/admin-sdk/directory/v1/guides/manage-mobile-devices#update_mobile_device).
* @param userAgent userAgent or {@code null} for none
*/
public MobileDevice setUserAgent(java.lang.String userAgent) {
this.userAgent = userAgent;
return this;
}
/**
* The device's MAC address on Wi-Fi networks.
* @return value or {@code null} for none
*/
public java.lang.String getWifiMacAddress() {
return wifiMacAddress;
}
/**
* The device's MAC address on Wi-Fi networks.
* @param wifiMacAddress wifiMacAddress or {@code null} for none
*/
public MobileDevice setWifiMacAddress(java.lang.String wifiMacAddress) {
this.wifiMacAddress = wifiMacAddress;
return this;
}
@Override
public MobileDevice set(String fieldName, Object value) {
return (MobileDevice) super.set(fieldName, value);
}
@Override
public MobileDevice clone() {
return (MobileDevice) super.clone();
}
/**
* Model definition for MobileDeviceApplications.
*/
public static final class Applications extends com.google.api.client.json.GenericJson {
/**
* The application's display name. An example is `Browser`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String displayName;
/**
* The application's package name. An example is `com.android.browser`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String packageName;
/**
* The list of permissions of this application. These can be either a standard Android permission
* or one defined by the application, and are found in an application's [Android
* manifest](https://developer.android.com/guide/topics/manifest/uses-permission-element.html).
* Examples of a Calendar application's permissions are `READ_CALENDAR`, or `MANAGE_ACCOUNTS`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> permission;
/**
* The application's version code. An example is `13`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer versionCode;
/**
* The application's version name. An example is `3.2-140714`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String versionName;
/**
* The application's display name. An example is `Browser`.
* @return value or {@code null} for none
*/
public java.lang.String getDisplayName() {
return displayName;
}
/**
* The application's display name. An example is `Browser`.
* @param displayName displayName or {@code null} for none
*/
public Applications setDisplayName(java.lang.String displayName) {
this.displayName = displayName;
return this;
}
/**
* The application's package name. An example is `com.android.browser`.
* @return value or {@code null} for none
*/
public java.lang.String getPackageName() {
return packageName;
}
/**
* The application's package name. An example is `com.android.browser`.
* @param packageName packageName or {@code null} for none
*/
public Applications setPackageName(java.lang.String packageName) {
this.packageName = packageName;
return this;
}
/**
* The list of permissions of this application. These can be either a standard Android permission
* or one defined by the application, and are found in an application's [Android
* manifest](https://developer.android.com/guide/topics/manifest/uses-permission-element.html).
* Examples of a Calendar application's permissions are `READ_CALENDAR`, or `MANAGE_ACCOUNTS`.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPermission() {
return permission;
}
/**
* The list of permissions of this application. These can be either a standard Android permission
* or one defined by the application, and are found in an application's [Android
* manifest](https://developer.android.com/guide/topics/manifest/uses-permission-element.html).
* Examples of a Calendar application's permissions are `READ_CALENDAR`, or `MANAGE_ACCOUNTS`.
* @param permission permission or {@code null} for none
*/
public Applications setPermission(java.util.List<java.lang.String> permission) {
this.permission = permission;
return this;
}
/**
* The application's version code. An example is `13`.
* @return value or {@code null} for none
*/
public java.lang.Integer getVersionCode() {
return versionCode;
}
/**
* The application's version code. An example is `13`.
* @param versionCode versionCode or {@code null} for none
*/
public Applications setVersionCode(java.lang.Integer versionCode) {
this.versionCode = versionCode;
return this;
}
/**
* The application's version name. An example is `3.2-140714`.
* @return value or {@code null} for none
*/
public java.lang.String getVersionName() {
return versionName;
}
/**
* The application's version name. An example is `3.2-140714`.
* @param versionName versionName or {@code null} for none
*/
public Applications setVersionName(java.lang.String versionName) {
this.versionName = versionName;
return this;
}
@Override
public Applications set(String fieldName, Object value) {
return (Applications) super.set(fieldName, value);
}
@Override
public Applications clone() {
return (Applications) super.clone();
}
}
}
|
googleapis/google-cloud-java | 38,067 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SubnetworkSecondaryRange.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* Represents a secondary IP range of a subnetwork.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SubnetworkSecondaryRange}
*/
public final class SubnetworkSecondaryRange extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SubnetworkSecondaryRange)
SubnetworkSecondaryRangeOrBuilder {
private static final long serialVersionUID = 0L;
// Use SubnetworkSecondaryRange.newBuilder() to construct.
private SubnetworkSecondaryRange(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SubnetworkSecondaryRange() {
ipCidrRange_ = "";
rangeName_ = "";
reservedInternalRange_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SubnetworkSecondaryRange();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SubnetworkSecondaryRange_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SubnetworkSecondaryRange.class,
com.google.cloud.compute.v1.SubnetworkSecondaryRange.Builder.class);
}
private int bitField0_;
public static final int IP_CIDR_RANGE_FIELD_NUMBER = 98117322;
@SuppressWarnings("serial")
private volatile java.lang.Object ipCidrRange_ = "";
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return Whether the ipCidrRange field is set.
*/
@java.lang.Override
public boolean hasIpCidrRange() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return The ipCidrRange.
*/
@java.lang.Override
public java.lang.String getIpCidrRange() {
java.lang.Object ref = ipCidrRange_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipCidrRange_ = s;
return s;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return The bytes for ipCidrRange.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIpCidrRangeBytes() {
java.lang.Object ref = ipCidrRange_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipCidrRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RANGE_NAME_FIELD_NUMBER = 332216397;
@SuppressWarnings("serial")
private volatile java.lang.Object rangeName_ = "";
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return Whether the rangeName field is set.
*/
@java.lang.Override
public boolean hasRangeName() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return The rangeName.
*/
@java.lang.Override
public java.lang.String getRangeName() {
java.lang.Object ref = rangeName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
rangeName_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return The bytes for rangeName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRangeNameBytes() {
java.lang.Object ref = rangeName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rangeName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESERVED_INTERNAL_RANGE_FIELD_NUMBER = 286248754;
@SuppressWarnings("serial")
private volatile java.lang.Object reservedInternalRange_ = "";
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return Whether the reservedInternalRange field is set.
*/
@java.lang.Override
public boolean hasReservedInternalRange() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return The reservedInternalRange.
*/
@java.lang.Override
public java.lang.String getReservedInternalRange() {
java.lang.Object ref = reservedInternalRange_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
reservedInternalRange_ = s;
return s;
}
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return The bytes for reservedInternalRange.
*/
@java.lang.Override
public com.google.protobuf.ByteString getReservedInternalRangeBytes() {
java.lang.Object ref = reservedInternalRange_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
reservedInternalRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 98117322, ipCidrRange_);
}
if (((bitField0_ & 0x00000004) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 286248754, reservedInternalRange_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 332216397, rangeName_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(98117322, ipCidrRange_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size +=
com.google.protobuf.GeneratedMessageV3.computeStringSize(
286248754, reservedInternalRange_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(332216397, rangeName_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.SubnetworkSecondaryRange)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.SubnetworkSecondaryRange other =
(com.google.cloud.compute.v1.SubnetworkSecondaryRange) obj;
if (hasIpCidrRange() != other.hasIpCidrRange()) return false;
if (hasIpCidrRange()) {
if (!getIpCidrRange().equals(other.getIpCidrRange())) return false;
}
if (hasRangeName() != other.hasRangeName()) return false;
if (hasRangeName()) {
if (!getRangeName().equals(other.getRangeName())) return false;
}
if (hasReservedInternalRange() != other.hasReservedInternalRange()) return false;
if (hasReservedInternalRange()) {
if (!getReservedInternalRange().equals(other.getReservedInternalRange())) 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 (hasIpCidrRange()) {
hash = (37 * hash) + IP_CIDR_RANGE_FIELD_NUMBER;
hash = (53 * hash) + getIpCidrRange().hashCode();
}
if (hasRangeName()) {
hash = (37 * hash) + RANGE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getRangeName().hashCode();
}
if (hasReservedInternalRange()) {
hash = (37 * hash) + RESERVED_INTERNAL_RANGE_FIELD_NUMBER;
hash = (53 * hash) + getReservedInternalRange().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.SubnetworkSecondaryRange prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Represents a secondary IP range of a subnetwork.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SubnetworkSecondaryRange}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SubnetworkSecondaryRange)
com.google.cloud.compute.v1.SubnetworkSecondaryRangeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SubnetworkSecondaryRange_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SubnetworkSecondaryRange.class,
com.google.cloud.compute.v1.SubnetworkSecondaryRange.Builder.class);
}
// Construct using com.google.cloud.compute.v1.SubnetworkSecondaryRange.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
ipCidrRange_ = "";
rangeName_ = "";
reservedInternalRange_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SubnetworkSecondaryRange_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.SubnetworkSecondaryRange getDefaultInstanceForType() {
return com.google.cloud.compute.v1.SubnetworkSecondaryRange.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.SubnetworkSecondaryRange build() {
com.google.cloud.compute.v1.SubnetworkSecondaryRange result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.SubnetworkSecondaryRange buildPartial() {
com.google.cloud.compute.v1.SubnetworkSecondaryRange result =
new com.google.cloud.compute.v1.SubnetworkSecondaryRange(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.SubnetworkSecondaryRange result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.ipCidrRange_ = ipCidrRange_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.rangeName_ = rangeName_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.reservedInternalRange_ = reservedInternalRange_;
to_bitField0_ |= 0x00000004;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.SubnetworkSecondaryRange) {
return mergeFrom((com.google.cloud.compute.v1.SubnetworkSecondaryRange) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.SubnetworkSecondaryRange other) {
if (other == com.google.cloud.compute.v1.SubnetworkSecondaryRange.getDefaultInstance())
return this;
if (other.hasIpCidrRange()) {
ipCidrRange_ = other.ipCidrRange_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasRangeName()) {
rangeName_ = other.rangeName_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasReservedInternalRange()) {
reservedInternalRange_ = other.reservedInternalRange_;
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 784938578:
{
ipCidrRange_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 784938578
case -2004977262:
{
reservedInternalRange_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case -2004977262
case -1637236118:
{
rangeName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case -1637236118
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 ipCidrRange_ = "";
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return Whether the ipCidrRange field is set.
*/
public boolean hasIpCidrRange() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return The ipCidrRange.
*/
public java.lang.String getIpCidrRange() {
java.lang.Object ref = ipCidrRange_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipCidrRange_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return The bytes for ipCidrRange.
*/
public com.google.protobuf.ByteString getIpCidrRangeBytes() {
java.lang.Object ref = ipCidrRange_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipCidrRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @param value The ipCidrRange to set.
* @return This builder for chaining.
*/
public Builder setIpCidrRange(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ipCidrRange_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @return This builder for chaining.
*/
public Builder clearIpCidrRange() {
ipCidrRange_ = getDefaultInstance().getIpCidrRange();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The range of IP addresses belonging to this subnetwork secondary range. Provide this property when you create the subnetwork. Ranges must be unique and non-overlapping with all primary and secondary IP ranges within a network. Only IPv4 is supported. The range can be any range listed in the Valid ranges list.
* </pre>
*
* <code>optional string ip_cidr_range = 98117322;</code>
*
* @param value The bytes for ipCidrRange to set.
* @return This builder for chaining.
*/
public Builder setIpCidrRangeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ipCidrRange_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object rangeName_ = "";
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return Whether the rangeName field is set.
*/
public boolean hasRangeName() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return The rangeName.
*/
public java.lang.String getRangeName() {
java.lang.Object ref = rangeName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
rangeName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return The bytes for rangeName.
*/
public com.google.protobuf.ByteString getRangeNameBytes() {
java.lang.Object ref = rangeName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rangeName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @param value The rangeName to set.
* @return This builder for chaining.
*/
public Builder setRangeName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
rangeName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @return This builder for chaining.
*/
public Builder clearRangeName() {
rangeName_ = getDefaultInstance().getRangeName();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name associated with this subnetwork secondary range, used when adding an alias IP range to a VM instance. The name must be 1-63 characters long, and comply with RFC1035. The name must be unique within the subnetwork.
* </pre>
*
* <code>optional string range_name = 332216397;</code>
*
* @param value The bytes for rangeName to set.
* @return This builder for chaining.
*/
public Builder setRangeNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
rangeName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object reservedInternalRange_ = "";
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return Whether the reservedInternalRange field is set.
*/
public boolean hasReservedInternalRange() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return The reservedInternalRange.
*/
public java.lang.String getReservedInternalRange() {
java.lang.Object ref = reservedInternalRange_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
reservedInternalRange_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return The bytes for reservedInternalRange.
*/
public com.google.protobuf.ByteString getReservedInternalRangeBytes() {
java.lang.Object ref = reservedInternalRange_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
reservedInternalRange_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @param value The reservedInternalRange to set.
* @return This builder for chaining.
*/
public Builder setReservedInternalRange(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
reservedInternalRange_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @return This builder for chaining.
*/
public Builder clearReservedInternalRange() {
reservedInternalRange_ = getDefaultInstance().getReservedInternalRange();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The URL of the reserved internal range.
* </pre>
*
* <code>optional string reserved_internal_range = 286248754;</code>
*
* @param value The bytes for reservedInternalRange to set.
* @return This builder for chaining.
*/
public Builder setReservedInternalRangeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
reservedInternalRange_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.SubnetworkSecondaryRange)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SubnetworkSecondaryRange)
private static final com.google.cloud.compute.v1.SubnetworkSecondaryRange DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.SubnetworkSecondaryRange();
}
public static com.google.cloud.compute.v1.SubnetworkSecondaryRange getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SubnetworkSecondaryRange> PARSER =
new com.google.protobuf.AbstractParser<SubnetworkSecondaryRange>() {
@java.lang.Override
public SubnetworkSecondaryRange 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<SubnetworkSecondaryRange> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SubnetworkSecondaryRange> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.SubnetworkSecondaryRange getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/sagetv | 38,136 | java/sage/Ministry.java | /*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sage;
// Transcoding Manager
public class Ministry implements Runnable
{
private static final String NEXT_JOB_ID = "transcoder/next_job_id";
protected static final String TRANSCODE_JOB_PROPS = "transcoder/jobs";
private static final String[] DEAD_FORMAT_NAMES = {
"Razr Compatible-Fair Quality",
"Razr Compatible-Good Quality",
"Razr Compatible-High Quality",
"MPEG4 HDTV Deinterlaced in AVI-High Quality",
"MPEG4 HDTV in AVI-High Quality",
"MPEG4 HDTV Deinterlaced in AVI-Good Quality",
"MPEG4 HDTV in AVI-Good Quality",
"MPEG4 Deinterlaced in AVI-High Quality",
"MPEG4 in AVI-High Quality",
"MPEG4 Deinterlaced in AVI-Good Quality",
"MPEG4 in AVI-Good Quality",
"PSP Compatible-Good Quality",
"PSP Compatible-High Quality",
"PSP Compatible Widescreen-Good Quality",
"PSP Compatible Widescreen-High Quality",
"iPod Compatible-Fair Quality",
"iPod Compatible-Good Quality",
"iPod Compatible-High Quality",
"DVD Compatible-Standard Play",
"DVD Compatible-Standard Play with AC3",
"DVD Compatible-Standard Play w/ AC3",
"DVD Compatible-Long Play",
"DVD Compatible-Long Play with AC3",
"DVD Compatible-Long Play w/ AC3",
"DVD Compatible-Extra Long Play",
"DVD Compatible-Extra Long Play with AC3",
"DVD Compatible-Extra Long Play w/ AC3",
"Razr-Fair Quality",
"Razr-Good Quality",
"Razr-High Quality",
"MPEG4 HDTV-High Quality Deinterlaced AVI",
"MPEG4 HDTV-Good Quality Deinterlaced AVI",
"MPEG4-High Quality Deinterlaced AVI",
"MPEG4-Good Quality Deinterlaced AVI",
};
private static final String[][] SUBSTITUTE_FORMAT_NAMES = {
{ "MPEG4 HDTV-High Quality Deinterlaced AVI", "MPEG4 HDTV-High Quality AVI" },
{ "MPEG4 HDTV-Good Quality Deinterlaced AVI", "MPEG4 HDTV-Good Quality AVI" },
{ "MPEG4-High Quality Deinterlaced AVI", "MPEG4-High Quality AVI" },
{ "MPEG4-Good Quality Deinterlaced AVI", "MPEG4-Good Quality AVI" },
};
// We got rid of the deinterlace options here since that's done automatically in FFMPEGTranscoder.java now (it'll add the -deinterlace flag if the input is
// interlaced and it's not scaling it down vertically by more than half)
public static final String[][] PREDEFINED_TRANSCODER_FORMATS = {
/* { "Razr-Fair Quality", "f=3gp;[bf=vid;f=mpeg4;br=80000;fps=29.97;w=176;h=144;][bf=aud;f=amr_nb;sr=8000;ch=1;bsmp=8;br=7950;]" },
{ "Razr-Good Quality", "f=3gp;[bf=vid;f=mpeg4;br=120000;fps=29.97;w=176;h=144;][bf=aud;f=amr_nb;sr=8000;ch=1;bsmp=8;br=7950;]" },
{ "Razr-High Quality", "f=3gp;[bf=vid;f=mpeg4;br=172000;fps=29.97;w=176;h=144;][bf=aud;f=amr_nb;sr=8000;ch=1;bsmp=8;br=7950;]" },
*/// { "MPEG4 HDTV-High Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=8000000;][bf=aud;]" },
{ "MPEG4 HDTV-High Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=8000000;][bf=aud;]" },
// { "MPEG4 HDTV-Good Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=6000000;][bf=aud;]" },
{ "MPEG4 HDTV-Good Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=6000000;][bf=aud;]" },
{ "MPEG4 HDTV-High Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method hex -subq 2 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 1 -directpred 1 -trellis 0 -flags2 +bpyramid-mixed_refs+wpred+dct8x8+fastpskip -wpredp 0 -rc_lookahead 10;[bf=vid;f=h264;br=7500000;][bf=aud;]" },
{ "MPEG4 HDTV-Good Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4-partp8x8-partb8x8 -me_method dia -subq 1 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 1 -directpred 1 -trellis 0 -flags2 +bpyramid-mixed_refs+wpred+dct8x8+fastpskip-mbtree -wpredp 0 -rc_lookahead 0;[bf=vid;f=h264;br=4500000;][bf=aud;]" },
{ "PSP-Good Quality", "f=psp;MCompressionDetails=-bitexact 1[bf=vid;f=xvid;br=216000;fps=29.97;w=320;h=240;][bf=aud;f=aac;sr=24000;ch=1;br=48000;]" },
{ "PSP-High Quality", "f=psp;MCompressionDetails=-bitexact 1[bf=vid;f=xvid;br=768000;fps=29.97;w=320;h=240;][bf=aud;f=aac;sr=24000;ch=2;br=128000;]" },
{ "PSP-Widescreen Good Quality", "f=psp;MCompressionDetails=-bitexact 1[bf=vid;f=xvid;br=216000;fps=29.97;w=368;h=208;][bf=aud;f=aac;sr=24000;ch=1;br=48000;]" },
{ "PSP-Widescreen High Quality", "f=psp;MCompressionDetails=-bitexact 1[bf=vid;f=xvid;br=768000;fps=29.97;w=368;h=208;][bf=aud;f=aac;sr=24000;ch=2;br=128000;]" },
/* TODO: ffmpeg now has ipod format handler */
{ "iPod-Fair Quality", "f=mp4;MCompressionDetails=-bufsize 33554432 -g 300;[bf=vid;f=mpeg4;br=500000;fps=29.97;w=512;h=384;arn=4;ard=3;][bf=aud;f=aac;sr=44100;ch=2;br=64000;]" },
{ "iPod-Good Quality", "f=mp4;MCompressionDetails=-maxrate 1250000 -bufsize 33554432 -g 300;[bf=vid;f=mpeg4;br=1000000;fps=29.97;w=512;h=384;arn=4;ard=3;][bf=aud;f=aac;sr=44100;ch=2;br=96000;]" },
{ "iPod-High Quality", "f=mp4;MCompressionDetails=-maxrate 2500000 -qmin 3 -qmax 5 -bufsize 33554432 -g 300;[bf=vid;f=mpeg4;br=1800000;fps=29.97;w=512;h=384;arn=4;ard=3;][bf=aud;f=aac;sr=44100;ch=2;br=128000;]" },
/* TODO: Someone recommended better settings for iPhone (investigate)
-r 29.97 -vcodec libx264 -s 480x272 -flags +loop -cmp +chroma -deblockalpha 0 -deblockbeta 0 -crf 24 -bt 256k -refs 1 -coder 0 -me umh -me_range 16 -subq 5 -partitions +parti4x4+parti8x8+partp8x8 -g 250 -keyint_min 25 -level 30 -qmin 10 -qmax 51 -trellis 2 -sc_threshold 40 -i_qfactor 0.71 -acodec libfaac -ab 128k -ar 48000 -ac 2
*/
{ "iPhone-Standard", "f=mp4;MCompressionDetails=-coder 0 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method umh -subq 8 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 2 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 0 -refs 5 -directpred 3 -trellis 1 -flags2 -wpred-dct8x8 -wpredp 0 -rc_lookahead 50 -level 13 -maxrate 768000 -bufsize 3000000 -async 50;[bf=vid;f=h264;br=640000;fps=29.97;w=480;h=368;arn=4;ard=3;][bf=aud;f=aac;sr=48000;ch=2;br=128000;]" },
{ "iPhone-Widescreen", "f=mp4;MCompressionDetails=-coder 0 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method umh -subq 8 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 2 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 0 -refs 5 -directpred 3 -trellis 1 -flags2 -wpred-dct8x8 -wpredp 0 -rc_lookahead 50 -level 13 -maxrate 768000 -bufsize 3000000 -async 50;[bf=vid;f=h264;br=640000;fps=29.97;w=480;h=272;arn=16;ard=9;][bf=aud;f=aac;sr=48000;ch=2;br=128000;]" },
{ "AppleTV-High Quality", "f=mp4;MCompressionDetails=-coder 0 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method umh -subq 8 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 2 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 0 -refs 1 -directpred 3 -trellis 1 -flags2 -wpred-dct8x8 -wpredp 0 -rc_lookahead 50 -level 30 -maxrate 10000000 -bufsize 10000000;[bf=vid;f=h264;br=2500000;fps=29.97;w=720;h=480;arn=4;ard=3;][bf=aud;f=aac;sr=48000;ch=2;br=128000;]" },
{ "AppleTV-High Quality Widescreen", "f=mp4;MCompressionDetails=-coder 0 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method umh -subq 8 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 2 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 0 -refs 1 -directpred 3 -trellis 1 -flags2 -wpred-dct8x8 -wpredp 0 -rc_lookahead 50 -level 30 -maxrate 10000000 -bufsize 10000000;[bf=vid;f=h264;br=2500000;fps=29.97;w=960;h=540;arn=16;ard=9;][bf=aud;f=aac;sr=48000;ch=2;br=128000;]" },
};
public static final String[][] PREDEFINED_TRANSCODER_FORMATS_NTSC = {
// { "MPEG4-High Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=2000000;w=720;h=480;fps=29.97;][bf=aud;]" },
{ "MPEG4-High Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=2000000;w=720;h=480;fps=29.97;][bf=aud;]" },
// { "MPEG4-Good Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=1500000;w=720;h=480;fps=29.97;][bf=aud;]" },
{ "MPEG4-Good Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=1500000;w=720;h=480;fps=29.97;][bf=aud;]" },
{ "MPEG4-High Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method hex -subq 6 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 2 -directpred 1 -trellis 1 -flags2 +bpyramid+mixed_refs+wpred+dct8x8+fastpskip -wpredp 2 -rc_lookahead 30;[bf=vid;f=h264;br=2000000;w=720;h=480;fps=29.97;][bf=aud;]" },
{ "MPEG4-Good Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4-partp8x8-partb8x8 -me_method dia -subq 1 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 1 -directpred 1 -trellis 0 -flags2 +bpyramid-mixed_refs+wpred+dct8x8+fastpskip-mbtree -wpredp 0 -rc_lookahead 0;[bf=vid;f=h264;br=1500000;w=720;h=480;fps=29.97;][bf=aud;]" },
{ "DVD-Standard Play", "f=dvd;[bf=vid;f=mpeg2video;br=6400000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Standard Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=6400000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
{ "DVD-Long Play", "f=dvd;[bf=vid;f=mpeg2video;br=4800000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Long Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=4800000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
{ "DVD-Extra Long Play", "f=dvd;[bf=vid;f=mpeg2video;br=3000000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Extra Long Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=3000000;fps=29.97;w=720;h=480;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
};
public static final String[][] PREDEFINED_TRANSCODER_FORMATS_PAL = {
// { "MPEG4-High Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=2000000;w=720;h=576;fps=25;][bf=aud;]" },
{ "MPEG4-High Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=2000000;w=720;h=576;fps=25;][bf=aud;]" },
// { "MPEG4-Good Quality Deinterlaced AVI", "f=avi;MCompressionDetails=-vtag xvid -deinterlace;[bf=vid;f=mpeg4;br=1500000;w=720;h=576;fps=25;][bf=aud;]" },
{ "MPEG4-Good Quality AVI", "f=avi;MCompressionDetails=-vtag xvid;[bf=vid;f=mpeg4;br=1500000;w=720;h=576;fps=25;][bf=aud;]" },
{ "MPEG4-High Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -me_method hex -subq 6 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 2 -directpred 1 -trellis 1 -flags2 +bpyramid+mixed_refs+wpred+dct8x8+fastpskip -wpredp 2 -rc_lookahead 30;[bf=vid;f=h264;br=2000000;w=720;h=576;fps=25;][bf=aud;]" },
{ "MPEG4-Good Quality H.264 MKV", "f=matroska;MCompressionDetails=-coder 1 -flags +loop -cmp +chroma -partitions +parti8x8+parti4x4-partp8x8-partb8x8 -me_method dia -subq 1 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -b_strategy 1 -qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -bf 3 -refs 1 -directpred 1 -trellis 0 -flags2 +bpyramid-mixed_refs+wpred+dct8x8+fastpskip-mbtree -wpredp 0 -rc_lookahead 0;[bf=vid;f=h264;br=1500000;w=720;h=576;fps=25;][bf=aud;]" },
{ "DVD-Standard Play", "f=dvd;[bf=vid;f=mpeg2video;br=6400000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Standard Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=6400000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
{ "DVD-Long Play", "f=dvd;[bf=vid;f=mpeg2video;br=4800000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Long Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=4800000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
{ "DVD-Extra Long Play", "f=dvd;[bf=vid;f=mpeg2video;br=3000000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=mp2;sr=48000;ch=2;bsmp=16;br=384000;]" },
{ "DVD-Extra Long Play with AC3", "f=dvd;[bf=vid;f=mpeg2video;br=3000000;fps=25;w=720;h=576;vbr=1;][bf=aud;f=ac3;sr=48000;bsmp=16;br=384000;]" },
};
private static class MinistryHolder
{
public static final Ministry instance = new Ministry();
}
public static Ministry getInstance()
{
return MinistryHolder.instance;
}
/** Creates a new instance of Ministry */
public Ministry()
{
jobCounter = Sage.getInt(NEXT_JOB_ID, 1);
for (int i = 0; i < DEAD_FORMAT_NAMES.length; i++)
Sage.remove("transcoder/formats/" + DEAD_FORMAT_NAMES[i]);
for (int i = 0; i < PREDEFINED_TRANSCODER_FORMATS.length; i++)
Sage.put("transcoder/formats/" + PREDEFINED_TRANSCODER_FORMATS[i][0], PREDEFINED_TRANSCODER_FORMATS[i][1]);
if (MMC.getInstance().isNTSCVideoFormat())
{
for (int i = 0; i < PREDEFINED_TRANSCODER_FORMATS_NTSC.length; i++)
Sage.put("transcoder/formats/" + PREDEFINED_TRANSCODER_FORMATS_NTSC[i][0], PREDEFINED_TRANSCODER_FORMATS_NTSC[i][1]);
}
else
{
for (int i = 0; i < PREDEFINED_TRANSCODER_FORMATS_PAL.length; i++)
Sage.put("transcoder/formats/" + PREDEFINED_TRANSCODER_FORMATS_PAL[i][0], PREDEFINED_TRANSCODER_FORMATS_PAL[i][1]);
}
}
public void notifyOfID(int x)
{
synchronized (idLock)
{
if (x >= jobCounter)
{
jobCounter = x + 1;
Sage.putInt(NEXT_JOB_ID, jobCounter);
}
}
}
public int getNextJobID()
{
synchronized (idLock)
{
Sage.putInt(NEXT_JOB_ID, jobCounter + 1);
jobCounter++;
return jobCounter - 1;
}
}
public void spawn()
{
alive = true;
ministryThread = new Thread(this, "Ministry");
ministryThread.setPriority(Thread.MIN_PRIORITY);
ministryThread.setDaemon(true);
ministryThread.start();
}
void goodbye()
{
alive = false;
synchronized (lock)
{
lock.notifyAll();
}
if (ministryThread != null)
{
try
{
ministryThread.join(10000);
}
catch (InterruptedException e){}
}
}
public void run()
{
// Just wait a sec at first so we don't slow down anything initializing since we're lowest priority
try{Thread.sleep(5000);}catch(Exception e){}
if (Sage.DBG) System.out.println("Ministry is starting");
// Look for any MediaFiles which we should mark as transcoded immediately
MediaFile[] mfs = Wizard.getInstance().getFiles();
for (int i = 0; i < mfs.length; i++)
{
MediaFile mf = mfs[i];
if (doesFileAlwaysRequireTranscoding(mf))
{
if (Sage.DBG) System.out.println("Added for transcoding:" + mf);
sage.media.format.ContainerFormat cf = new sage.media.format.ContainerFormat();
cf.setFormatName(sage.media.format.MediaFormat.AVI);
waitingForConversion.add(new DShowTranscodeJob(mf, "AVI", cf, true, null));
}
}
String[] jobKeys = Sage.childrenNames(TRANSCODE_JOB_PROPS);
for (int i = 0; i < jobKeys.length; i++)
{
int currJobID;
try
{
currJobID = Integer.parseInt(jobKeys[i]);
}
catch (NumberFormatException e)
{
System.out.println("ERROR in transcode job id format:" + e);
continue;
}
String processor = Sage.get(TRANSCODE_JOB_PROPS + '/' + currJobID + '/' + TranscodeJob.TRANSCODE_PROCESSOR, null);
TranscodeJob tj;
try
{
if ("sagetv".equals(processor))
{
tj = new FFMPEGTranscodeJob(currJobID);
}
else
{
System.out.println("Unknown Transcode processor:" + processor);
continue;
}
if (tj.getJobState() == TranscodeJob.COMPLETED || tj.getJobState() < 0)
waitingForAbsolution.add(tj);
else
waitingForConversion.add(tj);
}
catch (IllegalArgumentException iae)
{
System.out.println("BAD transcode job data:" + iae);
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + currJobID);
}
}
while (alive)
{
long waitTime = Sage.getLong("mstry_engine_update_frequency", 3*Sage.MILLIS_PER_MIN);
try
{
// Check if anything that's waiting to be converted is now ready for the conversion queue
if (!waitingForConversion.isEmpty())
{
for (int i = 0; i < waitingForConversion.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForConversion.get(i);
if (tj.isReadyForConversion())
{
waitingForConversion.removeElementAt(i);
startConversion(tj);
}
else if (tj.hasLostHope())
{
waitingForConversion.removeElementAt(i);
}
else
{
waitTime = Math.min(waitTime, tj.getWaitTime());
}
}
}
synchronized (converting)
{
if (converting.size() > 0)
{
TranscodeJob mainConvert = (TranscodeJob) converting.get(0);
switch (mainConvert.getJobState())
{
case TranscodeJob.WAITING:
mainConvert.startTranscode();
dirty = true;
break;
case TranscodeJob.TRANSCODING:
break;
case TranscodeJob.TRANSCODE_FAILED:
converting.remove(0);
waitingForAbsolution.add(mainConvert);
mainConvert.cleanupCurrentTranscode();
mainConvert.abandon();
dirty = true;
break;
case TranscodeJob.DESTROYED:
converting.remove(0);
mainConvert.cleanupCurrentTranscode();
mainConvert.abandon();
dirty = true;
break;
case TranscodeJob.TRANSCODING_SEGMENT_COMPLETE:
mainConvert.cleanupCurrentTranscode();
if (mainConvert.getClipDuration() == 0 || mainConvert.transcodeSegment < mainConvert.getEndingSegment())
mainConvert.getTempFile(mainConvert.transcodeSegment).setLastModified(mainConvert.getMediaFile().
getEnd(mainConvert.transcodeSegment));
else
mainConvert.getTempFile(mainConvert.transcodeSegment).setLastModified(mainConvert.getMediaFile().
getRecordTime() + mainConvert.getClipStartTime() + mainConvert.getClipDuration());
if (mainConvert.transcodeSegment < mainConvert.getEndingSegment())
{
mainConvert.continueTranscode();
}
else
{
mainConvert.setJobState(TranscodeJob.LIMBO);
converting.remove(0);
waitingForAbsolution.add(mainConvert);
}
dirty = true;
break;
}
}
}
Hunter seek = SeekerSelector.getInstance();
for (int i = 0; i < waitingForAbsolution.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.get(i);
if (tj.getJobState() == TranscodeJob.COMPLETED || tj.getJobState() < 0)
continue;
if (Sage.DBG) System.out.println("Ministry is absolving " + tj.getMediaFile());
if (tj.shouldReplaceOriginal() && seek.isMediaFileBeingViewed(tj.getMediaFile()))
{
if (Sage.DBG) System.out.println("Waiting to perform transcode DB update until file use has completed.");
continue;
}
java.io.File[] newFiles = tj.getTargetFiles();
java.io.File[] currFiles = tj.getTempFiles();
java.util.ArrayList actualFilesVec = new java.util.ArrayList();
for (int j = tj.getStartingSegment(); j <= tj.getEndingSegment(); j++)
{
actualFilesVec.add(newFiles[j]);
seek.addIgnoreFile(newFiles[j]);
if (!currFiles[j].equals(newFiles[j]) && (tj.shouldReplaceOriginal() || !newFiles[j].equals(tj.getMediaFile().getFile(j))))
newFiles[j].delete(); // delete the target file so we can rename appropriately
if (!currFiles[j].renameTo(newFiles[j]))
{
if (Sage.DBG) System.out.println("Renaming of transcoded file " + currFiles[j] + " failed to " + newFiles[j]);
}
}
boolean ok;
if (tj.shouldReplaceOriginal())
{
if (tj.getClipStartTime() != 0 || tj.getClipDuration() != 0)
{
long theStart = tj.getClipStartTime() + tj.getMediaFile().getRecordTime();
long clipDur = tj.getClipDuration();
long theEnd;
if (clipDur != 0)
theEnd = theStart + clipDur;
else
theEnd = tj.getMediaFile().getRecordEnd();
ok = tj.getMediaFile().setFiles((java.io.File[]) actualFilesVec.toArray(new java.io.File[0]), theStart, theEnd);
tj.getMediaFile().thisIsComplete();
}
else
ok = tj.getMediaFile().setFiles((java.io.File[]) actualFilesVec.toArray(new java.io.File[0]));
if (!ok)
{
for (int j = tj.getStartingSegment(); j <= tj.getEndingSegment(); j++)
{
if (!newFiles[j].renameTo(currFiles[j]))
{
if (Sage.DBG) System.out.println("Re-renaming of transcoded file " + newFiles[j] + " failed to " + currFiles[j]);
}
}
}
else
SeekerSelector.getInstance().processFileExport(tj.getMediaFile().getFiles(), MediaFile.ACQUISITION_MANUAL);
}
else
{
if (Sage.getBoolean("transcoder/dont_add_converted_duplicate_files_to_db", false))
{
ok = true;
}
else
{
MediaFile addedFile = Wizard.getInstance().addMediaFile(newFiles[tj.getStartingSegment()], "", MediaFile.ACQUISITION_MANUAL);
if (addedFile != null)
{
if (addedFile.isArchiveFile() != tj.getMediaFile().isArchiveFile())
{
if (tj.getMediaFile().isArchiveFile())
addedFile.simpleArchive();
else
addedFile.simpleUnarchive();
}
// Copy any auxillary metadata
sage.media.format.ContainerFormat cf = tj.getMediaFile().getFileFormat();
if (cf != null && cf.hasMetadata())
{
// We need to do it one by one so that the external .properties file gets updated (instead of addMetadata that does it all at once)
java.util.Properties metaProps = cf.getMetadata();
java.util.Iterator walker = metaProps.entrySet().iterator();
while (walker.hasNext())
{
java.util.Map.Entry ent = (java.util.Map.Entry) walker.next();
if (ent.getKey() != null && ent.getValue() != null)
addedFile.addMetadata(ent.getKey().toString(), ent.getValue().toString());
}
}
if (Sage.DBG) System.out.println("New Library File " + addedFile);
if (tj.getClipStartTime() == 0 && tj.getClipDuration() == 0)
{
// Converted the whole thing, so use the complete airing.
addedFile.setInfoAiring(Wizard.getInstance().addAiring(tj.getMediaFile().getShow(), 0,
tj.getMediaFile().getContentAiring().getStartTime(),
tj.getMediaFile().getContentAiring().getDuration(),
tj.getMediaFile().getContentAiring().partsB, tj.getMediaFile().getContentAiring().miscB,
tj.getMediaFile().getContentAiring().prB, tj.getMediaFile().getMediaMask()));
}
else
{
long airStart = tj.getMediaFile().getRecordTime() + tj.getClipStartTime();
addedFile.setInfoAiring(Wizard.getInstance().addAiring(tj.getMediaFile().getShow(), 0,
airStart, (tj.getClipDuration() == 0) ?
(tj.getMediaFile().getRecordEnd() - airStart) : tj.getClipDuration(),
tj.getMediaFile().getContentAiring().partsB, tj.getMediaFile().getContentAiring().miscB,
tj.getMediaFile().getContentAiring().prB, tj.getMediaFile().getMediaMask()));
}
for (int x = 1; x < newFiles.length; x++)
{
addedFile.addSegmentFileDirect((java.io.File) actualFilesVec.get(x));
}
ok = true;
SeekerSelector.getInstance().processFileExport(addedFile.getFiles(), MediaFile.ACQUISITION_MANUAL);
}
else
ok = false;
}
}
for (int j = 0; j < newFiles.length; j++)
{
seek.removeIgnoreFile(newFiles[j]);
}
// It might not be ready yet for some reason if there's a lock on a file
if (ok)
{
// It's all done
//waitingForAbsolution.remove(i--);
tj.setJobState(TranscodeJob.COMPLETED);
if (tj instanceof FFMPEGTranscodeJob)
tj.saveToProps();
}
if (tj.hasLostHope())
tj.abandon();
}
}
catch (Throwable t)
{
System.out.println("ERROR Occured in core of Ministry:" + t);
t.printStackTrace();
}
synchronized (lock)
{
if (!dirty)
{
try
{
if (Sage.DBG) System.out.println("Ministry is waiting for " + waitTime/1000 + " sec");
lock.wait(waitTime);
}catch(Exception e){}
}
}
dirty = false;
}
// Abandon all current transcode jobs since we're shutting down
if (Sage.DBG) System.out.println("Ministry is shutting down....destroying the converts in progress");
while (waitingForAbsolution.size() > 0)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.remove(0);
tj.cleanupCurrentTranscode();
tj.abandon();
}
while (converting.size() > 0)
{
TranscodeJob tj = (TranscodeJob) converting.remove(0);
tj.cleanupCurrentTranscode();
tj.abandon();
}
}
public static sage.media.format.ContainerFormat getPredefinedTargetFormat(String formatName)
{
for (int i = 0; i < SUBSTITUTE_FORMAT_NAMES.length; i++)
{
if (SUBSTITUTE_FORMAT_NAMES[i][0].equalsIgnoreCase(formatName))
{
formatName = SUBSTITUTE_FORMAT_NAMES[i][1];
break;
}
}
return sage.media.format.ContainerFormat.buildFormatFromString(Sage.get("transcoder/formats/" + formatName, null));
}
public void submitForPotentialTranscoding(MediaFile mf)
{
if (doesFileAlwaysRequireTranscoding(mf))
{
synchronized (waitingForConversion)
{
for (int i = 0; i < waitingForConversion.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForConversion.get(i);
if (tj.getMediaFile() == mf)
return;
}
if (Sage.DBG) System.out.println("Added for transcoding:" + mf);
sage.media.format.ContainerFormat cf = new sage.media.format.ContainerFormat();
cf.setFormatName(sage.media.format.MediaFormat.AVI);
waitingForConversion.add(new DShowTranscodeJob(mf, "AVI", cf, true, null));
}
kick();
}
else
{
// Check for a Favorite auto conversion
String targetFormat = Carny.getInstance().getAutoConvertFormat(mf);
if (targetFormat != null && targetFormat.length() > 0)
{
if (Sage.DBG) System.out.println("Setting up automatic Favorite conversion to format " + targetFormat + " for " + mf);
java.io.File destDir = Carny.getInstance().getAutoConvertDest(mf);
if (destDir != null)
destDir.mkdirs();
addTranscodeJob(mf, targetFormat, getPredefinedTargetFormat(targetFormat),
destDir, Carny.getInstance().isDeleteAfterConversion(mf), 0, 0);
}
}
}
public int addTranscodeJob(MediaFile srcFile, String formatName, sage.media.format.ContainerFormat theFormat, java.io.File destFile,
boolean deleteSourceAfter, long clipStartTime, long clipDuration)
{
TranscodeJob tj;
synchronized (waitingForConversion)
{
if (Sage.DBG) System.out.println("Added for transcoding:" + srcFile);
tj = new FFMPEGTranscodeJob(srcFile, formatName, theFormat, deleteSourceAfter, destFile,
clipStartTime, clipDuration);
tj.saveToProps();
waitingForConversion.add(tj);
}
kick();
return tj.getJobID();
}
public void clearCompletedTranscodes()
{
synchronized (waitingForAbsolution)
{
for (int i = 0; i < waitingForAbsolution.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.get(i);
if (tj.getJobState() == TranscodeJob.COMPLETED || tj.getJobState() < 0)
{
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + tj.getJobID());
waitingForAbsolution.removeElementAt(i--);
}
}
}
}
public boolean cancelTranscodeJob(int jobID)
{
boolean rv = false;
synchronized (waitingForConversion)
{
for (int i = 0; i < waitingForConversion.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForConversion.get(i);
if (tj.getJobID() == jobID)
{
if (Sage.DBG) System.out.println("KillTranscoding for:" + tj.getMediaFile());
tj.cleanupCurrentTranscode();
tj.abandon();
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + tj.getJobID());
waitingForConversion.removeElementAt(i);
rv = true;
break;
}
}
}
synchronized (converting)
{
for (int i = 0; !rv && i < converting.size(); i++)
{
TranscodeJob tj = (TranscodeJob) converting.get(i);
if (tj.getJobID() == jobID)
{
if (Sage.DBG) System.out.println("KillTranscoding for:" + tj.getMediaFile());
tj.cleanupCurrentTranscode();
tj.abandon();
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + tj.getJobID());
converting.removeElementAt(i);
rv = true;
break;
}
}
}
synchronized (waitingForAbsolution)
{
for (int i = 0; !rv && i < waitingForAbsolution.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.get(i);
if (tj.getJobID() == jobID)
{
if (Sage.DBG) System.out.println("KillTranscoding for:" + tj.getMediaFile());
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + tj.getJobID());
waitingForAbsolution.removeElementAt(i);
rv = true;
break;
}
}
}
if (rv)
kick();
return rv;
}
protected TranscodeJob getJobForID(int jobID)
{
synchronized (waitingForConversion)
{
for (int i = 0; i < waitingForConversion.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForConversion.get(i);
if (tj.getJobID() == jobID)
return tj;
}
}
synchronized (converting)
{
for (int i = 0; i < converting.size(); i++)
{
TranscodeJob tj = (TranscodeJob) converting.get(i);
if (tj.getJobID() == jobID)
return tj;
}
}
synchronized (waitingForAbsolution)
{
for (int i = 0; i < waitingForAbsolution.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.get(i);
if (tj.getJobID() == jobID)
return tj;
}
}
return null;
}
public int getJobStatusCode(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? -1 : tj.getJobState();
}
public MediaFile getJobSourceFile(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? null : tj.getMediaFile();
}
public java.io.File getJobDestFile(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? null : tj.getDestFile();
}
public String getJobFormat(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? "" : tj.getTargetFormatName();
}
public float getJobPercentComplete(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? 0 : tj.getPercentComplete();
}
public boolean getJobShouldKeepOriginal(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? false : !tj.shouldReplaceOriginal();
}
public long getJobClipStartTime(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? 0 : tj.getClipStartTime();
}
public long getJobClipDuration(int jobID)
{
TranscodeJob tj = getJobForID(jobID);
return (tj == null) ? 0 : tj.getClipDuration();
}
public int[] getTranscodeJobIDs()
{
java.util.ArrayList rv = new java.util.ArrayList();
synchronized (waitingForConversion)
{
for (int i = 0; i < waitingForConversion.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForConversion.get(i);
rv.add(new Integer(tj.getJobID()));
}
}
synchronized (converting)
{
for (int i = 0; i < converting.size(); i++)
{
TranscodeJob tj = (TranscodeJob) converting.get(i);
rv.add(new Integer(tj.getJobID()));
}
}
synchronized (waitingForAbsolution)
{
for (int i = 0; i < waitingForAbsolution.size(); i++)
{
TranscodeJob tj = (TranscodeJob) waitingForAbsolution.get(i);
rv.add(new Integer(tj.getJobID()));
}
}
int[] irv = new int[rv.size()];
for (int i = 0; i < rv.size(); i++)
irv[i] = ((Integer) rv.get(i)).intValue();
return irv;
}
public void killTranscoding(MediaFile mf)
{
// IT SHOULD FIND THE MF'S JOB IF IT HAS ONE AND THEN KILL THE FILTER GRAPH, IT MUST
// WAIT UNTIL ITS KILLED SO ITS SURE IT CAN DELETE THE FILES BECAUSE WE DON'T WANT THE SOURCE FILTER
// TO BE HOLDING THEM OPEN. THEN IT NEEDS TO REMOVE THEM FROM OUR QUEUES ALSO
boolean changed = false;
synchronized (converting)
{
for (int i = 0; i < converting.size(); i++)
{
TranscodeJob tj = (TranscodeJob) converting.get(i);
if (tj.getMediaFile() == mf)
{
if (Sage.DBG) System.out.println("KillTranscoding for:" + mf);
tj.cleanupCurrentTranscode();
tj.abandon();
tj.setJobState(TranscodeJob.DESTROYED);
converting.removeElementAt(i);
Sage.removeNode(TRANSCODE_JOB_PROPS + '/' + tj.getJobID());
changed = true;
break;
}
}
}
if (changed)
kick();
}
public boolean doesFileAlwaysRequireTranscoding(MediaFile mf)
{
return sage.media.format.MediaFormat.MPEG2_PS.equals(mf.getContainerFormat()) &&
sage.media.format.MediaFormat.MPEG4X.equals(mf.getPrimaryVideoFormat()) && !mf.isAnyLiveStream();
}
public void kick()
{
dirty = true;
synchronized (lock)
{
lock.notifyAll();
}
}
private void startConversion(TranscodeJob tj)
{
tj.setJobState(TranscodeJob.WAITING);
converting.add(tj);
}
public boolean isValidSourceFormat(sage.media.format.ContainerFormat cf)
{
// We can transcode anything without DRM that's not WMV9 or WMALossless
if (cf == null || cf.isDRMProtected() ||
// sage.media.format.MediaFormat.WMV9.equals(cf.getPrimaryVideoFormat()) ||
sage.media.format.MediaFormat.WMA9LOSSLESS.equals(cf.getPrimaryAudioFormat()))
return false;
else
return true;
}
public boolean requiresPower()
{
// This is true if there's any transcode jobs are in the queue
synchronized (this)
{
return (converting.size() > 0 || waitingForConversion.size() > 0);
}
}
private Object lock = new Object();
private java.util.Vector waitingForConversion = new java.util.Vector();
private java.util.Vector converting = new java.util.Vector();
private java.util.Vector waitingForAbsolution = new java.util.Vector();
private boolean dirty = false;
private boolean alive;
private Thread ministryThread;
private int jobCounter;
private Object idLock = new Object();
}
|
googleapis/google-cloud-java | 37,962 | java-iap/proto-google-cloud-iap-v1/src/main/java/com/google/cloud/iap/v1/TunnelDestGroup.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/iap/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.iap.v1;
/**
*
*
* <pre>
* A TunnelDestGroup.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.TunnelDestGroup}
*/
public final class TunnelDestGroup extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iap.v1.TunnelDestGroup)
TunnelDestGroupOrBuilder {
private static final long serialVersionUID = 0L;
// Use TunnelDestGroup.newBuilder() to construct.
private TunnelDestGroup(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private TunnelDestGroup() {
name_ = "";
cidrs_ = com.google.protobuf.LazyStringArrayList.emptyList();
fqdns_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new TunnelDestGroup();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_TunnelDestGroup_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_TunnelDestGroup_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.TunnelDestGroup.class,
com.google.cloud.iap.v1.TunnelDestGroup.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CIDRS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList cidrs_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the cidrs.
*/
public com.google.protobuf.ProtocolStringList getCidrsList() {
return cidrs_;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of cidrs.
*/
public int getCidrsCount() {
return cidrs_.size();
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The cidrs at the given index.
*/
public java.lang.String getCidrs(int index) {
return cidrs_.get(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the cidrs at the given index.
*/
public com.google.protobuf.ByteString getCidrsBytes(int index) {
return cidrs_.getByteString(index);
}
public static final int FQDNS_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList fqdns_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the fqdns.
*/
public com.google.protobuf.ProtocolStringList getFqdnsList() {
return fqdns_;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of fqdns.
*/
public int getFqdnsCount() {
return fqdns_.size();
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The fqdns at the given index.
*/
public java.lang.String getFqdns(int index) {
return fqdns_.get(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the fqdns at the given index.
*/
public com.google.protobuf.ByteString getFqdnsBytes(int index) {
return fqdns_.getByteString(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
for (int i = 0; i < cidrs_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, cidrs_.getRaw(i));
}
for (int i = 0; i < fqdns_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, fqdns_.getRaw(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
{
int dataSize = 0;
for (int i = 0; i < cidrs_.size(); i++) {
dataSize += computeStringSizeNoTag(cidrs_.getRaw(i));
}
size += dataSize;
size += 1 * getCidrsList().size();
}
{
int dataSize = 0;
for (int i = 0; i < fqdns_.size(); i++) {
dataSize += computeStringSizeNoTag(fqdns_.getRaw(i));
}
size += dataSize;
size += 1 * getFqdnsList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.iap.v1.TunnelDestGroup)) {
return super.equals(obj);
}
com.google.cloud.iap.v1.TunnelDestGroup other = (com.google.cloud.iap.v1.TunnelDestGroup) obj;
if (!getName().equals(other.getName())) return false;
if (!getCidrsList().equals(other.getCidrsList())) return false;
if (!getFqdnsList().equals(other.getFqdnsList())) 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 (getCidrsCount() > 0) {
hash = (37 * hash) + CIDRS_FIELD_NUMBER;
hash = (53 * hash) + getCidrsList().hashCode();
}
if (getFqdnsCount() > 0) {
hash = (37 * hash) + FQDNS_FIELD_NUMBER;
hash = (53 * hash) + getFqdnsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.TunnelDestGroup parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.iap.v1.TunnelDestGroup 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 TunnelDestGroup.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.TunnelDestGroup}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iap.v1.TunnelDestGroup)
com.google.cloud.iap.v1.TunnelDestGroupOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_TunnelDestGroup_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_TunnelDestGroup_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.TunnelDestGroup.class,
com.google.cloud.iap.v1.TunnelDestGroup.Builder.class);
}
// Construct using com.google.cloud.iap.v1.TunnelDestGroup.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
cidrs_ = com.google.protobuf.LazyStringArrayList.emptyList();
fqdns_ = com.google.protobuf.LazyStringArrayList.emptyList();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_TunnelDestGroup_descriptor;
}
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroup getDefaultInstanceForType() {
return com.google.cloud.iap.v1.TunnelDestGroup.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroup build() {
com.google.cloud.iap.v1.TunnelDestGroup result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroup buildPartial() {
com.google.cloud.iap.v1.TunnelDestGroup result =
new com.google.cloud.iap.v1.TunnelDestGroup(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.iap.v1.TunnelDestGroup result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
cidrs_.makeImmutable();
result.cidrs_ = cidrs_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
fqdns_.makeImmutable();
result.fqdns_ = fqdns_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.iap.v1.TunnelDestGroup) {
return mergeFrom((com.google.cloud.iap.v1.TunnelDestGroup) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iap.v1.TunnelDestGroup other) {
if (other == com.google.cloud.iap.v1.TunnelDestGroup.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.cidrs_.isEmpty()) {
if (cidrs_.isEmpty()) {
cidrs_ = other.cidrs_;
bitField0_ |= 0x00000002;
} else {
ensureCidrsIsMutable();
cidrs_.addAll(other.cidrs_);
}
onChanged();
}
if (!other.fqdns_.isEmpty()) {
if (fqdns_.isEmpty()) {
fqdns_ = other.fqdns_;
bitField0_ |= 0x00000004;
} else {
ensureFqdnsIsMutable();
fqdns_.addAll(other.fqdns_);
}
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
ensureCidrsIsMutable();
cidrs_.add(s);
break;
} // case 18
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
ensureFqdnsIsMutable();
fqdns_.add(s);
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Identifier. Identifier for the TunnelDestGroup. Must be unique within the
* project and contain only lower case letters (a-z) and dashes (-).
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.protobuf.LazyStringArrayList cidrs_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureCidrsIsMutable() {
if (!cidrs_.isModifiable()) {
cidrs_ = new com.google.protobuf.LazyStringArrayList(cidrs_);
}
bitField0_ |= 0x00000002;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the cidrs.
*/
public com.google.protobuf.ProtocolStringList getCidrsList() {
cidrs_.makeImmutable();
return cidrs_;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of cidrs.
*/
public int getCidrsCount() {
return cidrs_.size();
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The cidrs at the given index.
*/
public java.lang.String getCidrs(int index) {
return cidrs_.get(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the cidrs at the given index.
*/
public com.google.protobuf.ByteString getCidrsBytes(int index) {
return cidrs_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index to set the value at.
* @param value The cidrs to set.
* @return This builder for chaining.
*/
public Builder setCidrs(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureCidrsIsMutable();
cidrs_.set(index, value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The cidrs to add.
* @return This builder for chaining.
*/
public Builder addCidrs(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureCidrsIsMutable();
cidrs_.add(value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param values The cidrs to add.
* @return This builder for chaining.
*/
public Builder addAllCidrs(java.lang.Iterable<java.lang.String> values) {
ensureCidrsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, cidrs_);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearCidrs() {
cidrs_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of CIDRs that this group applies to.
* </pre>
*
* <code>
* repeated string cidrs = 2 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The bytes of the cidrs to add.
* @return This builder for chaining.
*/
public Builder addCidrsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureCidrsIsMutable();
cidrs_.add(value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.LazyStringArrayList fqdns_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureFqdnsIsMutable() {
if (!fqdns_.isModifiable()) {
fqdns_ = new com.google.protobuf.LazyStringArrayList(fqdns_);
}
bitField0_ |= 0x00000004;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the fqdns.
*/
public com.google.protobuf.ProtocolStringList getFqdnsList() {
fqdns_.makeImmutable();
return fqdns_;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of fqdns.
*/
public int getFqdnsCount() {
return fqdns_.size();
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The fqdns at the given index.
*/
public java.lang.String getFqdns(int index) {
return fqdns_.get(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the fqdns at the given index.
*/
public com.google.protobuf.ByteString getFqdnsBytes(int index) {
return fqdns_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index to set the value at.
* @param value The fqdns to set.
* @return This builder for chaining.
*/
public Builder setFqdns(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureFqdnsIsMutable();
fqdns_.set(index, value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The fqdns to add.
* @return This builder for chaining.
*/
public Builder addFqdns(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureFqdnsIsMutable();
fqdns_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param values The fqdns to add.
* @return This builder for chaining.
*/
public Builder addAllFqdns(java.lang.Iterable<java.lang.String> values) {
ensureFqdnsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, fqdns_);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearFqdns() {
fqdns_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Unordered list. List of FQDNs that this group applies to.
* </pre>
*
* <code>
* repeated string fqdns = 3 [(.google.api.field_behavior) = UNORDERED_LIST, (.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The bytes of the fqdns to add.
* @return This builder for chaining.
*/
public Builder addFqdnsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureFqdnsIsMutable();
fqdns_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.iap.v1.TunnelDestGroup)
}
// @@protoc_insertion_point(class_scope:google.cloud.iap.v1.TunnelDestGroup)
private static final com.google.cloud.iap.v1.TunnelDestGroup DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iap.v1.TunnelDestGroup();
}
public static com.google.cloud.iap.v1.TunnelDestGroup getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<TunnelDestGroup> PARSER =
new com.google.protobuf.AbstractParser<TunnelDestGroup>() {
@java.lang.Override
public TunnelDestGroup 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<TunnelDestGroup> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<TunnelDestGroup> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iap.v1.TunnelDestGroup getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/gora | 38,321 | gora-elasticsearch/src/main/java/org/apache/gora/elasticsearch/store/ElasticsearchStore.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.gora.elasticsearch.store;
import org.apache.avro.Schema;
import org.apache.avro.util.Utf8;
import org.apache.gora.elasticsearch.mapping.ElasticsearchMapping;
import org.apache.gora.elasticsearch.mapping.ElasticsearchMappingBuilder;
import org.apache.gora.elasticsearch.mapping.Field;
import org.apache.gora.elasticsearch.query.ElasticsearchQuery;
import org.apache.gora.elasticsearch.query.ElasticsearchResult;
import org.apache.gora.elasticsearch.utils.ElasticsearchParameters;
import org.apache.gora.filter.Filter;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.persistency.impl.BeanFactoryImpl;
import org.apache.gora.persistency.impl.DirtyListWrapper;
import org.apache.gora.persistency.impl.DirtyMapWrapper;
import org.apache.gora.persistency.impl.PersistentBase;
import org.apache.gora.query.PartitionQuery;
import org.apache.gora.query.Query;
import org.apache.gora.query.Result;
import org.apache.gora.query.impl.PartitionQueryImpl;
import org.apache.gora.store.impl.DataStoreBase;
import org.apache.gora.util.AvroUtils;
import org.apache.gora.util.ClassLoadingUtils;
import org.apache.gora.util.GoraException;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.flush.FlushRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.index.reindex.UpdateByQueryRequest;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
* Implementation of a Apache Elasticsearch data store to be used by Apache Gora.
*
* @param <K> class to be used for the key
* @param <T> class to be persisted within the store
*/
public class ElasticsearchStore<K, T extends PersistentBase> extends DataStoreBase<K, T> {
public static final Logger LOG = LoggerFactory.getLogger(ElasticsearchStore.class);
private static final String DEFAULT_MAPPING_FILE = "gora-elasticsearch-mapping.xml";
public static final String PARSE_MAPPING_FILE_KEY = "gora.elasticsearch.mapping.file";
private static final String XML_MAPPING_DEFINITION = "gora.mapping";
public static final String XSD_VALIDATION = "gora.xsd_validation";
/**
* Elasticsearch client
*/
private RestHighLevelClient client;
/**
* Mapping definition for Elasticsearch
*/
private ElasticsearchMapping elasticsearchMapping;
@Override
public void initialize(Class<K> keyClass, Class<T> persistentClass, Properties properties) throws GoraException {
try {
LOG.debug("Initializing Elasticsearch store");
ElasticsearchParameters parameters = ElasticsearchParameters.load(properties, getConf());
super.initialize(keyClass, persistentClass, properties);
ElasticsearchMappingBuilder<K, T> builder = new ElasticsearchMappingBuilder<>(this);
InputStream mappingStream;
if (properties.containsKey(XML_MAPPING_DEFINITION)) {
if (LOG.isTraceEnabled()) {
LOG.trace("{} = {}", XML_MAPPING_DEFINITION, properties.getProperty(XML_MAPPING_DEFINITION));
}
mappingStream = org.apache.commons.io.IOUtils.toInputStream(properties.getProperty(XML_MAPPING_DEFINITION), (Charset) null);
} else {
mappingStream = getClass().getClassLoader().getResourceAsStream(properties.getProperty(PARSE_MAPPING_FILE_KEY, DEFAULT_MAPPING_FILE));
}
String xsdValidation = properties.getProperty(XSD_VALIDATION, "false");
builder.readMappingFile(mappingStream, Boolean.parseBoolean(xsdValidation));
elasticsearchMapping = builder.getElasticsearchMapping();
client = createClient(parameters);
LOG.info("Elasticsearch store was successfully initialized.");
} catch (Exception ex) {
LOG.error("Error while initializing Elasticsearch store", ex);
throw new GoraException(ex);
}
}
public static RestHighLevelClient createClient(ElasticsearchParameters parameters) {
RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(parameters.getHost(), parameters.getPort()));
// Choosing the authentication method.
switch (parameters.getAuthenticationType()) {
case BASIC:
if (parameters.getUsername() != null && parameters.getPassword() != null) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(parameters.getUsername(), parameters.getPassword()));
clientBuilder.setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
} else {
throw new IllegalArgumentException("Missing username or password for BASIC authentication.");
}
break;
case TOKEN:
if (parameters.getAuthorizationToken() != null) {
Header[] defaultHeaders = new Header[]{new BasicHeader("Authorization",
parameters.getAuthorizationToken())};
clientBuilder.setDefaultHeaders(defaultHeaders);
} else {
throw new IllegalArgumentException("Missing authorization token for TOKEN authentication.");
}
break;
case APIKEY:
if (parameters.getApiKeyId() != null && parameters.getApiKeySecret() != null) {
String apiKeyAuth = Base64.getEncoder()
.encodeToString((parameters.getApiKeyId() + ":" + parameters.getApiKeySecret())
.getBytes(StandardCharsets.UTF_8));
Header[] defaultHeaders = new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKeyAuth)};
clientBuilder.setDefaultHeaders(defaultHeaders);
} else {
throw new IllegalArgumentException("Missing API Key ID or API Key Secret for APIKEY authentication.");
}
break;
}
if (parameters.getConnectTimeout() != 0) {
clientBuilder.setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder.setConnectTimeout(parameters.getConnectTimeout()));
}
if (parameters.getSocketTimeout() != 0) {
clientBuilder.setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder.setSocketTimeout(parameters.getSocketTimeout()));
}
if (parameters.getIoThreadCount() != 0) {
clientBuilder.setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom()
.setIoThreadCount(parameters.getIoThreadCount()).build()));
}
return new RestHighLevelClient(clientBuilder);
}
public ElasticsearchMapping getMapping() {
return elasticsearchMapping;
}
@Override
public String getSchemaName() {
return elasticsearchMapping.getIndexName();
}
@Override
public String getSchemaName(final String mappingSchemaName, final Class<?> persistentClass) {
return super.getSchemaName(mappingSchemaName, persistentClass);
}
@Override
public void createSchema() throws GoraException {
CreateIndexRequest request = new CreateIndexRequest(elasticsearchMapping.getIndexName());
Map<String, Object> properties = new HashMap<>();
for (Map.Entry<String, Field> entry : elasticsearchMapping.getFields().entrySet()) {
Map<String, Object> fieldType = new HashMap<>();
fieldType.put("type", entry.getValue().getDataType().getType().name().toLowerCase(Locale.ROOT));
if (entry.getValue().getDataType().getType() == Field.DataType.SCALED_FLOAT) {
fieldType.put("scaling_factor", entry.getValue().getDataType().getScalingFactor());
}
properties.put(entry.getKey(), fieldType);
}
// Special field for range query
properties.put("gora_id", new HashMap<String, Object>() {{
put("type", "keyword");
}});
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping);
try {
if (!client.indices().exists(
new GetIndexRequest(elasticsearchMapping.getIndexName()), RequestOptions.DEFAULT)) {
client.indices().create(request, RequestOptions.DEFAULT);
}
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public void deleteSchema() throws GoraException {
DeleteIndexRequest request = new DeleteIndexRequest(elasticsearchMapping.getIndexName());
try {
if (client.indices().exists(
new GetIndexRequest(elasticsearchMapping.getIndexName()), RequestOptions.DEFAULT)) {
client.indices().delete(request, RequestOptions.DEFAULT);
}
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public boolean schemaExists() throws GoraException {
try {
return client.indices().exists(
new GetIndexRequest(elasticsearchMapping.getIndexName()), RequestOptions.DEFAULT);
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public boolean exists(K key) throws GoraException {
GetRequest getRequest = new GetRequest(elasticsearchMapping.getIndexName(), (String) key);
getRequest.fetchSourceContext(new FetchSourceContext(false)).storedFields("_none_");
try {
return client.exists(getRequest, RequestOptions.DEFAULT);
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public T get(K key, String[] fields) throws GoraException {
String[] requestedFields = getFieldsToQuery(fields);
List<String> documentFields = new ArrayList<>();
for (String requestedField : requestedFields) {
documentFields.add(elasticsearchMapping.getFields().get(requestedField).getName());
}
try {
// Prepare the Elasticsearch request
GetRequest getRequest = new GetRequest(elasticsearchMapping.getIndexName(), (String) key);
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
if (getResponse.isExists()) {
Map<String, Object> sourceMap = getResponse.getSourceAsMap();
// Map of field's name and its value from the Document
Map<String, Object> fieldsAndValues = new HashMap<>();
for (String field : documentFields) {
fieldsAndValues.put(field, sourceMap.get(field));
}
// Build the corresponding persistent
return newInstance(fieldsAndValues, requestedFields);
} else {
return null;
}
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public void put(K key, T obj) throws GoraException {
if (obj.isDirty()) {
Schema schemaObj = obj.getSchema();
List<Schema.Field> fields = schemaObj.getFields();
Map<String, Object> jsonMap = new HashMap<>();
for (Schema.Field field : fields) {
Field mappedField = elasticsearchMapping.getFields().get(field.name());
if (mappedField != null) {
Object fieldValue = obj.get(field.pos());
if (fieldValue != null) {
Schema fieldSchema = field.schema();
Object serializedObj = serializeFieldValue(fieldSchema, fieldValue);
jsonMap.put(mappedField.getName(), serializedObj);
}
}
}
// Special field for range query
jsonMap.put("gora_id", key);
// Prepare the Elasticsearch request
IndexRequest request = new IndexRequest(elasticsearchMapping.getIndexName()).id((String) key).source(jsonMap);
try {
client.index(request, RequestOptions.DEFAULT);
} catch (IOException ex) {
throw new GoraException(ex);
}
} else {
LOG.info("Ignored putting object {} in the store as it is neither "
+ "new, neither dirty.", new Object[]{obj});
}
}
@Override
public boolean delete(K key) throws GoraException {
DeleteRequest request = new DeleteRequest(elasticsearchMapping.getIndexName(), (String) key);
try {
DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
return deleteResponse.getResult() != DocWriteResponse.Result.NOT_FOUND;
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public long deleteByQuery(Query<K, T> query) throws GoraException {
try {
BulkByScrollResponse bulkResponse;
if (query.getFields() != null && query.getFields().length < elasticsearchMapping.getFields().size()) {
UpdateByQueryRequest updateRequest = new UpdateByQueryRequest(elasticsearchMapping.getIndexName());
QueryBuilder matchDocumentsWithinRange = QueryBuilders
.rangeQuery("gora_id").from(query.getStartKey()).to(query.getEndKey());
updateRequest.setQuery(matchDocumentsWithinRange);
// Create a script for deleting fields
StringBuilder toDelete = new StringBuilder();
String[] fieldsToDelete = query.getFields();
for (String field : fieldsToDelete) {
String elasticsearchField = elasticsearchMapping.getFields().get(field).getName();
toDelete.append(String.format(Locale.getDefault(), "ctx._source.remove('%s');", elasticsearchField));
}
//toDelete.deleteCharAt(toDelete.length() - 1);
updateRequest.setScript(new Script(ScriptType.INLINE, "painless", toDelete.toString(), Collections.emptyMap()));
bulkResponse = client.updateByQuery(updateRequest, RequestOptions.DEFAULT);
return bulkResponse.getUpdated();
} else {
DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(elasticsearchMapping.getIndexName());
QueryBuilder matchDocumentsWithinRange = QueryBuilders
.rangeQuery("gora_id").from(query.getStartKey()).to(query.getEndKey());
deleteRequest.setQuery(matchDocumentsWithinRange);
bulkResponse = client.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
return bulkResponse.getDeleted();
}
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public Result<K, T> execute(Query<K, T> query) throws GoraException {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// Set the query result limit
int size = (int) query.getLimit();
if (size != -1) {
searchSourceBuilder.size(size);
}
try {
// Build the actual Elasticsearch range query
QueryBuilder rangeQueryBuilder = QueryBuilders
.rangeQuery("gora_id").gte(query.getStartKey()).lte(query.getEndKey());
searchSourceBuilder.query(rangeQueryBuilder);
SearchRequest searchRequest = new SearchRequest(elasticsearchMapping.getIndexName());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
String[] avroFields = getFieldsToQuery(query.getFields());
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
List<K> hitId = new ArrayList<>();
// Check filter
Filter<K, T> queryFilter = query.getFilter();
List<T> filteredObjects = new ArrayList<>();
for (SearchHit hit : searchHits) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
if (queryFilter == null || !queryFilter.filter((K) hit.getId(), newInstance(sourceAsMap, avroFields))) {
filteredObjects.add(newInstance(sourceAsMap, avroFields));
hitId.add((K) hit.getId());
}
}
return new ElasticsearchResult<>(this, query, hitId, filteredObjects);
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public Query<K, T> newQuery() {
ElasticsearchQuery<K, T> query = new ElasticsearchQuery<>(this);
query.setFields(getFieldsToQuery(null));
return query;
}
@Override
public List<PartitionQuery<K, T>> getPartitions(Query<K, T> query) throws IOException {
List<PartitionQuery<K, T>> partitions = new ArrayList<>();
PartitionQueryImpl<K, T> partitionQuery = new PartitionQueryImpl<>(
query);
partitionQuery.setConf(getConf());
partitions.add(partitionQuery);
return partitions;
}
@Override
public void flush() throws GoraException {
try {
client.indices().refresh(new RefreshRequest(elasticsearchMapping.getIndexName()), RequestOptions.DEFAULT);
client.indices().flush(new FlushRequest(elasticsearchMapping.getIndexName()), RequestOptions.DEFAULT);
} catch (IOException ex) {
throw new GoraException(ex);
}
}
@Override
public void close() {
try {
client.close();
LOG.info("Elasticsearch datastore destroyed successfully.");
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
}
}
/**
* Build a new instance of the persisted class from the Document retrieved from the database.
*
* @param fieldsAndValues Map of field's name and its value from the Document
* that results from the query to the database
* @param requestedFields the list of fields to be mapped to the persistence class instance
* @return a persistence class instance which content was deserialized from the Document
* @throws IOException
*/
public T newInstance(Map<String, Object> fieldsAndValues, String[] requestedFields) throws IOException {
// Create new empty persistent bean instance
T persistent = newPersistent();
requestedFields = getFieldsToQuery(requestedFields);
// Populate each field
for (String objField : requestedFields) {
Schema.Field field = fieldMap.get(objField);
Schema fieldSchema = field.schema();
String docFieldName = elasticsearchMapping.getFields().get(objField).getName();
Object fieldValue = fieldsAndValues.get(docFieldName);
Object result = deserializeFieldValue(field, fieldSchema, fieldValue);
persistent.put(field.pos(), result);
}
persistent.clearDirty();
return persistent;
}
/**
* Deserialize an Elasticsearch object to a persistent Avro object.
*
* @param avroField persistent Avro class field to which the value will be deserialized
* @param avroFieldSchema schema for the persistent Avro class field
* @param elasticsearchValue Elasticsearch field value to be deserialized
* @return deserialized Avro object from the Elasticsearch object
* @throws GoraException when the given Elasticsearch value cannot be deserialized
*/
private Object deserializeFieldValue(Schema.Field avroField, Schema avroFieldSchema,
Object elasticsearchValue) throws GoraException {
Object fieldValue;
switch (avroFieldSchema.getType()) {
case MAP:
fieldValue = fromElasticsearchMap(avroField, avroFieldSchema.getValueType(), (Map<String, Object>) elasticsearchValue);
break;
case RECORD:
fieldValue = fromElasticsearchRecord(avroFieldSchema, (Map<String, Object>) elasticsearchValue);
break;
case ARRAY:
fieldValue = fromElasticsearchList(avroField, avroFieldSchema.getElementType(), elasticsearchValue);
break;
case BOOLEAN:
fieldValue = Boolean.parseBoolean(elasticsearchValue.toString());
break;
case BYTES:
fieldValue = ByteBuffer.wrap(Base64.getDecoder().decode(elasticsearchValue.toString()));
break;
case FIXED:
case NULL:
fieldValue = null;
break;
case UNION:
fieldValue = fromElasticsearchUnion(avroField, avroFieldSchema, elasticsearchValue);
break;
case DOUBLE:
fieldValue = Double.parseDouble(elasticsearchValue.toString());
break;
case ENUM:
fieldValue = AvroUtils.getEnumValue(avroFieldSchema, elasticsearchValue.toString());
break;
case FLOAT:
fieldValue = Float.parseFloat(elasticsearchValue.toString());
break;
case INT:
fieldValue = Integer.parseInt(elasticsearchValue.toString());
break;
case LONG:
fieldValue = Long.parseLong(elasticsearchValue.toString());
break;
case STRING:
fieldValue = new Utf8(elasticsearchValue.toString());
break;
default:
fieldValue = elasticsearchValue;
}
return fieldValue;
}
/**
* Deserialize an Elasticsearch List to an Avro List as used in Gora generated classes
* that can safely be written into Avro persistent object.
*
* @param avroField persistent Avro class field to which the value will be deserialized
* @param avroFieldSchema schema for the persistent Avro class field
* @param elasticsearchValue Elasticsearch field value to be deserialized
* @return deserialized Avro List from the given Elasticsearch value
* @throws GoraException when one of the underlying values cannot be deserialized
*/
private Object fromElasticsearchList(Schema.Field avroField, Schema avroFieldSchema,
Object elasticsearchValue) throws GoraException {
List<Object> list = new ArrayList<>();
if (elasticsearchValue != null) {
for (Object item : (List<Object>) elasticsearchValue) {
Object result = deserializeFieldValue(avroField, avroFieldSchema, item);
list.add(result);
}
}
return new DirtyListWrapper<>(list);
}
/**
* Deserialize an Elasticsearch Map to an Avro Map as used in Gora generated classes
* that can safely be written into Avro persistent object.
*
* @param avroField persistent Avro class field to which the value will be deserialized
* @param avroFieldSchema schema for the persistent Avro class field
* @param elasticsearchMap Elasticsearch Map value to be deserialized
* @return deserialized Avro Map from the given Elasticsearch Map value
* @throws GoraException when one of the underlying values cannot be deserialized
*/
private Object fromElasticsearchMap(Schema.Field avroField, Schema avroFieldSchema,
Map<String, Object> elasticsearchMap) throws GoraException {
Map<Utf8, Object> deserializedMap = new HashMap<>();
if (elasticsearchMap != null) {
for (Map.Entry<String, Object> entry : elasticsearchMap.entrySet()) {
String mapKey = entry.getKey();
Object mapValue = deserializeFieldValue(avroField, avroFieldSchema, entry.getValue());
deserializedMap.put(new Utf8(mapKey), mapValue);
}
}
return new DirtyMapWrapper<>(deserializedMap);
}
/**
* Deserialize an Elasticsearch Record to an Avro Object as used in Gora generated classes
* that can safely be written into Avro persistent object.
*
* @param avroFieldSchema schema for the persistent Avro class field
* @param elasticsearchRecord Elasticsearch Record value to be deserialized
* @return deserialized Avro Object from the given Elasticsearch Record value
* @throws GoraException when one of the underlying values cannot be deserialized
*/
private Object fromElasticsearchRecord(Schema avroFieldSchema,
Map<String, Object> elasticsearchRecord) throws GoraException {
Class<?> clazz;
try {
clazz = ClassLoadingUtils.loadClass(avroFieldSchema.getFullName());
} catch (ClassNotFoundException ex) {
throw new GoraException(ex);
}
PersistentBase record = (PersistentBase) new BeanFactoryImpl(keyClass, clazz).newPersistent();
for (Schema.Field recField : avroFieldSchema.getFields()) {
Schema innerSchema = recField.schema();
Field innerDocField = elasticsearchMapping.getFields().getOrDefault(recField.name(), new Field(recField.name(), null));
record.put(recField.pos(), deserializeFieldValue(recField, innerSchema, elasticsearchRecord.get(innerDocField.getName())));
}
return record;
}
/**
* Deserialize an Elasticsearch Union to an Avro Object as used in Gora generated classes
* that can safely be written into Avro persistent object.
*
* @param avroField persistent Avro class field to which the value will be deserialized
* @param avroFieldSchema schema for the persistent Avro class field
* @param elasticsearchUnion Elasticsearch Union value to be deserialized
* @return deserialized Avro Object from the given Elasticsearch Union value
* @throws GoraException when one of the underlying values cannot be deserialized
*/
private Object fromElasticsearchUnion(Schema.Field avroField, Schema avroFieldSchema, Object elasticsearchUnion) throws GoraException {
Object deserializedUnion;
Schema.Type type0 = avroFieldSchema.getTypes().get(0).getType();
Schema.Type type1 = avroFieldSchema.getTypes().get(1).getType();
if (avroFieldSchema.getTypes().size() == 2 &&
(type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL)) &&
!type0.equals(type1)) {
int schemaPos = getUnionSchema(elasticsearchUnion, avroFieldSchema);
Schema unionSchema = avroFieldSchema.getTypes().get(schemaPos);
deserializedUnion = deserializeFieldValue(avroField, unionSchema, elasticsearchUnion);
} else if (avroFieldSchema.getTypes().size() == 3) {
Schema.Type type2 = avroFieldSchema.getTypes().get(2).getType();
if ((type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL) || type2.equals(Schema.Type.NULL)) &&
(type0.equals(Schema.Type.STRING) || type1.equals(Schema.Type.STRING) || type2.equals(Schema.Type.STRING))) {
if (elasticsearchUnion == null) {
deserializedUnion = null;
} else if (elasticsearchUnion instanceof String) {
throw new GoraException("Elasticsearch supports Union data type only represented as Record or Null.");
} else {
int schemaPos = getUnionSchema(elasticsearchUnion, avroFieldSchema);
Schema unionSchema = avroFieldSchema.getTypes().get(schemaPos);
deserializedUnion = fromElasticsearchRecord(unionSchema, (Map<String, Object>) elasticsearchUnion);
}
} else {
throw new GoraException("Elasticsearch only supports Union of two types field: Record or Null.");
}
} else {
throw new GoraException("Elasticsearch only supports Union of two types field: Record or Null.");
}
return deserializedUnion;
}
/**
* Serialize a persistent Avro object as used in Gora generated classes to
* an object that can be written into Elasticsearch.
*
* @param avroFieldSchema schema for the persistent Avro class field
* @param avroFieldValue persistent Avro field value to be serialized
* @return serialized field value
* @throws GoraException when the given Avro object cannot be serialized
*/
private Object serializeFieldValue(Schema avroFieldSchema, Object avroFieldValue) throws GoraException {
Object output = avroFieldValue;
switch (avroFieldSchema.getType()) {
case ARRAY:
output = arrayToElasticsearch((List<?>) avroFieldValue, avroFieldSchema.getElementType());
break;
case MAP:
output = mapToElasticsearch((Map<CharSequence, ?>) avroFieldValue, avroFieldSchema.getValueType());
break;
case RECORD:
output = recordToElasticsearch(avroFieldValue, avroFieldSchema);
break;
case BYTES:
output = Base64.getEncoder().encodeToString(((ByteBuffer) avroFieldValue).array());
break;
case UNION:
output = unionToElasticsearch(avroFieldValue, avroFieldSchema);
break;
case BOOLEAN:
case DOUBLE:
case ENUM:
case FLOAT:
case INT:
case LONG:
case STRING:
output = avroFieldValue.toString();
break;
case FIXED:
break;
case NULL:
output = null;
break;
}
return output;
}
/**
* Serialize a Java collection of persistent Avro objects as used in Gora generated classes to a
* List that can safely be written into Elasticsearch.
*
* @param collection the collection to be serialized
* @param avroFieldSchema field schema for the underlying type
* @return a List version of the collection that can be safely written into Elasticsearch
* @throws GoraException when one of the underlying values cannot be serialized
*/
private List<Object> arrayToElasticsearch(Collection<?> collection, Schema avroFieldSchema) throws GoraException {
List<Object> list = new ArrayList<>();
for (Object item : collection) {
Object result = serializeFieldValue(avroFieldSchema, item);
list.add(result);
}
return list;
}
/**
* Serialize a Java map of persistent Avro objects as used in Gora generated classes to a
* map that can safely be written into Elasticsearch.
*
* @param map the map to be serialized
* @param avroFieldSchema field schema for the underlying type
* @return a Map version of the Java map that can be safely written into Elasticsearch
* @throws GoraException when one of the underlying values cannot be serialized
*/
private Map<CharSequence, ?> mapToElasticsearch(Map<CharSequence, ?> map, Schema avroFieldSchema) throws GoraException {
Map<CharSequence, Object> serializedMap = new HashMap<>();
for (Map.Entry<CharSequence, ?> entry : map.entrySet()) {
String mapKey = entry.getKey().toString();
Object mapValue = entry.getValue();
Object result = serializeFieldValue(avroFieldSchema, mapValue);
serializedMap.put(mapKey, result);
}
return serializedMap;
}
/**
* Serialize a Java object of persistent Avro objects as used in Gora generated classes to a
* record that can safely be written into Elasticsearch.
*
* @param record the object to be serialized
* @param avroFieldSchema field schema for the underlying type
* @return a record version of the Java object that can be safely written into Elasticsearch
* @throws GoraException when one of the underlying values cannot be serialized
*/
private Map<CharSequence, Object> recordToElasticsearch(Object record, Schema avroFieldSchema) throws GoraException {
Map<CharSequence, Object> serializedRecord = new HashMap<>();
for (Schema.Field member : avroFieldSchema.getFields()) {
Object innerValue = ((PersistentBase) record).get(member.pos());
serializedRecord.put(member.name(), serializeFieldValue(member.schema(), innerValue));
}
return serializedRecord;
}
/**
* Serialize a Java object of persistent Avro objects as used in Gora generated classes to a
* object that can safely be written into Elasticsearch.
*
* @param union the object to be serialized
* @param avroFieldSchema field schema for the underlying type
* @return a object version of the Java object that can be safely written into Elasticsearch
* @throws GoraException when one of the underlying values cannot be serialized
*/
private Object unionToElasticsearch(Object union, Schema avroFieldSchema) throws GoraException {
Object serializedUnion;
Schema.Type type0 = avroFieldSchema.getTypes().get(0).getType();
Schema.Type type1 = avroFieldSchema.getTypes().get(1).getType();
if (avroFieldSchema.getTypes().size() == 2 &&
(type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL)) &&
!type0.equals(type1)) {
int schemaPos = getUnionSchema(union, avroFieldSchema);
Schema unionSchema = avroFieldSchema.getTypes().get(schemaPos);
serializedUnion = serializeFieldValue(unionSchema, union);
} else if (avroFieldSchema.getTypes().size() == 3) {
Schema.Type type2 = avroFieldSchema.getTypes().get(2).getType();
if ((type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL) || type2.equals(Schema.Type.NULL)) &&
(type0.equals(Schema.Type.STRING) || type1.equals(Schema.Type.STRING) || type2.equals(Schema.Type.STRING))) {
if (union == null) {
serializedUnion = null;
} else if (union instanceof String) {
throw new GoraException("Elasticsearch does not support foreign key IDs in Union data type.");
} else {
int schemaPos = getUnionSchema(union, avroFieldSchema);
Schema unionSchema = avroFieldSchema.getTypes().get(schemaPos);
serializedUnion = recordToElasticsearch(union, unionSchema);
}
} else {
throw new GoraException("Elasticsearch only supports Union of two types field: Record or Null.");
}
} else {
throw new GoraException("Elasticsearch only supports Union of two types field: Record or Null.");
}
return serializedUnion;
}
/**
* Method to retrieve the corresponding schema type index of a particular
* object having UNION schema. As UNION type can have one or more types and at
* a given instance, it holds an object of only one type of the defined types,
* this method is used to figure out the corresponding instance's schema type
* index.
*
* @param instanceValue value that the object holds
* @param unionSchema union schema containing all of the data types
* @return the unionSchemaPosition corresponding schema position
*/
private int getUnionSchema(Object instanceValue, Schema unionSchema) {
int unionSchemaPos = 0;
for (Schema currentSchema : unionSchema.getTypes()) {
Schema.Type schemaType = currentSchema.getType();
if (instanceValue instanceof CharSequence && schemaType.equals(Schema.Type.STRING)) {
return unionSchemaPos;
}
if (instanceValue instanceof ByteBuffer && schemaType.equals(Schema.Type.BYTES)) {
return unionSchemaPos;
}
if (instanceValue instanceof byte[] && schemaType.equals(Schema.Type.BYTES)) {
return unionSchemaPos;
}
if (instanceValue instanceof String && schemaType.equals(Schema.Type.BYTES)) {
return unionSchemaPos;
}
if (instanceValue instanceof Integer && schemaType.equals(Schema.Type.INT)) {
return unionSchemaPos;
}
if (instanceValue instanceof Long && schemaType.equals(Schema.Type.LONG)) {
return unionSchemaPos;
}
if (instanceValue instanceof Double && schemaType.equals(Schema.Type.DOUBLE)) {
return unionSchemaPos;
}
if (instanceValue instanceof Float && schemaType.equals(Schema.Type.FLOAT)) {
return unionSchemaPos;
}
if (instanceValue instanceof Boolean && schemaType.equals(Schema.Type.BOOLEAN)) {
return unionSchemaPos;
}
if (instanceValue instanceof Map && schemaType.equals(Schema.Type.MAP)) {
return unionSchemaPos;
}
if (instanceValue instanceof List && schemaType.equals(Schema.Type.ARRAY)) {
return unionSchemaPos;
}
if (instanceValue instanceof Persistent && schemaType.equals(Schema.Type.RECORD)) {
return unionSchemaPos;
}
if (instanceValue instanceof Map && schemaType.equals(Schema.Type.RECORD)) {
return unionSchemaPos;
}
if (instanceValue instanceof byte[] && schemaType.equals(Schema.Type.MAP)) {
return unionSchemaPos;
}
if (instanceValue instanceof byte[] && schemaType.equals(Schema.Type.RECORD)) {
return unionSchemaPos;
}
if (instanceValue instanceof byte[] && schemaType.equals(Schema.Type.ARRAY)) {
return unionSchemaPos;
}
unionSchemaPos++;
}
return 0;
}
}
|
googleapis/google-cloud-java | 38,049 | java-apihub/proto-google-cloud-apihub-v1/src/main/java/com/google/cloud/apihub/v1/ListPluginInstancesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/apihub/v1/plugin_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apihub.v1;
/**
*
*
* <pre>
* The
* [ListPluginInstances][google.cloud.apihub.v1.ApiHubPlugin.ListPluginInstances]
* method's response.
* </pre>
*
* Protobuf type {@code google.cloud.apihub.v1.ListPluginInstancesResponse}
*/
public final class ListPluginInstancesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apihub.v1.ListPluginInstancesResponse)
ListPluginInstancesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListPluginInstancesResponse.newBuilder() to construct.
private ListPluginInstancesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListPluginInstancesResponse() {
pluginInstances_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListPluginInstancesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apihub.v1.PluginServiceProto
.internal_static_google_cloud_apihub_v1_ListPluginInstancesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apihub.v1.PluginServiceProto
.internal_static_google_cloud_apihub_v1_ListPluginInstancesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apihub.v1.ListPluginInstancesResponse.class,
com.google.cloud.apihub.v1.ListPluginInstancesResponse.Builder.class);
}
public static final int PLUGIN_INSTANCES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.apihub.v1.PluginInstance> pluginInstances_;
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.apihub.v1.PluginInstance> getPluginInstancesList() {
return pluginInstances_;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.apihub.v1.PluginInstanceOrBuilder>
getPluginInstancesOrBuilderList() {
return pluginInstances_;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
@java.lang.Override
public int getPluginInstancesCount() {
return pluginInstances_.size();
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
@java.lang.Override
public com.google.cloud.apihub.v1.PluginInstance getPluginInstances(int index) {
return pluginInstances_.get(index);
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
@java.lang.Override
public com.google.cloud.apihub.v1.PluginInstanceOrBuilder getPluginInstancesOrBuilder(int index) {
return pluginInstances_.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 < pluginInstances_.size(); i++) {
output.writeMessage(1, pluginInstances_.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 < pluginInstances_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, pluginInstances_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.apihub.v1.ListPluginInstancesResponse)) {
return super.equals(obj);
}
com.google.cloud.apihub.v1.ListPluginInstancesResponse other =
(com.google.cloud.apihub.v1.ListPluginInstancesResponse) obj;
if (!getPluginInstancesList().equals(other.getPluginInstancesList())) 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 (getPluginInstancesCount() > 0) {
hash = (37 * hash) + PLUGIN_INSTANCES_FIELD_NUMBER;
hash = (53 * hash) + getPluginInstancesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.apihub.v1.ListPluginInstancesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The
* [ListPluginInstances][google.cloud.apihub.v1.ApiHubPlugin.ListPluginInstances]
* method's response.
* </pre>
*
* Protobuf type {@code google.cloud.apihub.v1.ListPluginInstancesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apihub.v1.ListPluginInstancesResponse)
com.google.cloud.apihub.v1.ListPluginInstancesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apihub.v1.PluginServiceProto
.internal_static_google_cloud_apihub_v1_ListPluginInstancesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apihub.v1.PluginServiceProto
.internal_static_google_cloud_apihub_v1_ListPluginInstancesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apihub.v1.ListPluginInstancesResponse.class,
com.google.cloud.apihub.v1.ListPluginInstancesResponse.Builder.class);
}
// Construct using com.google.cloud.apihub.v1.ListPluginInstancesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (pluginInstancesBuilder_ == null) {
pluginInstances_ = java.util.Collections.emptyList();
} else {
pluginInstances_ = null;
pluginInstancesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apihub.v1.PluginServiceProto
.internal_static_google_cloud_apihub_v1_ListPluginInstancesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.apihub.v1.ListPluginInstancesResponse getDefaultInstanceForType() {
return com.google.cloud.apihub.v1.ListPluginInstancesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apihub.v1.ListPluginInstancesResponse build() {
com.google.cloud.apihub.v1.ListPluginInstancesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apihub.v1.ListPluginInstancesResponse buildPartial() {
com.google.cloud.apihub.v1.ListPluginInstancesResponse result =
new com.google.cloud.apihub.v1.ListPluginInstancesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.apihub.v1.ListPluginInstancesResponse result) {
if (pluginInstancesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
pluginInstances_ = java.util.Collections.unmodifiableList(pluginInstances_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.pluginInstances_ = pluginInstances_;
} else {
result.pluginInstances_ = pluginInstancesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.apihub.v1.ListPluginInstancesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.apihub.v1.ListPluginInstancesResponse) {
return mergeFrom((com.google.cloud.apihub.v1.ListPluginInstancesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apihub.v1.ListPluginInstancesResponse other) {
if (other == com.google.cloud.apihub.v1.ListPluginInstancesResponse.getDefaultInstance())
return this;
if (pluginInstancesBuilder_ == null) {
if (!other.pluginInstances_.isEmpty()) {
if (pluginInstances_.isEmpty()) {
pluginInstances_ = other.pluginInstances_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePluginInstancesIsMutable();
pluginInstances_.addAll(other.pluginInstances_);
}
onChanged();
}
} else {
if (!other.pluginInstances_.isEmpty()) {
if (pluginInstancesBuilder_.isEmpty()) {
pluginInstancesBuilder_.dispose();
pluginInstancesBuilder_ = null;
pluginInstances_ = other.pluginInstances_;
bitField0_ = (bitField0_ & ~0x00000001);
pluginInstancesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPluginInstancesFieldBuilder()
: null;
} else {
pluginInstancesBuilder_.addAllMessages(other.pluginInstances_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.apihub.v1.PluginInstance m =
input.readMessage(
com.google.cloud.apihub.v1.PluginInstance.parser(), extensionRegistry);
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
pluginInstances_.add(m);
} else {
pluginInstancesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.apihub.v1.PluginInstance> pluginInstances_ =
java.util.Collections.emptyList();
private void ensurePluginInstancesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
pluginInstances_ =
new java.util.ArrayList<com.google.cloud.apihub.v1.PluginInstance>(pluginInstances_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apihub.v1.PluginInstance,
com.google.cloud.apihub.v1.PluginInstance.Builder,
com.google.cloud.apihub.v1.PluginInstanceOrBuilder>
pluginInstancesBuilder_;
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public java.util.List<com.google.cloud.apihub.v1.PluginInstance> getPluginInstancesList() {
if (pluginInstancesBuilder_ == null) {
return java.util.Collections.unmodifiableList(pluginInstances_);
} else {
return pluginInstancesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public int getPluginInstancesCount() {
if (pluginInstancesBuilder_ == null) {
return pluginInstances_.size();
} else {
return pluginInstancesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public com.google.cloud.apihub.v1.PluginInstance getPluginInstances(int index) {
if (pluginInstancesBuilder_ == null) {
return pluginInstances_.get(index);
} else {
return pluginInstancesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder setPluginInstances(int index, com.google.cloud.apihub.v1.PluginInstance value) {
if (pluginInstancesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePluginInstancesIsMutable();
pluginInstances_.set(index, value);
onChanged();
} else {
pluginInstancesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder setPluginInstances(
int index, com.google.cloud.apihub.v1.PluginInstance.Builder builderForValue) {
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
pluginInstances_.set(index, builderForValue.build());
onChanged();
} else {
pluginInstancesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder addPluginInstances(com.google.cloud.apihub.v1.PluginInstance value) {
if (pluginInstancesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePluginInstancesIsMutable();
pluginInstances_.add(value);
onChanged();
} else {
pluginInstancesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder addPluginInstances(int index, com.google.cloud.apihub.v1.PluginInstance value) {
if (pluginInstancesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePluginInstancesIsMutable();
pluginInstances_.add(index, value);
onChanged();
} else {
pluginInstancesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder addPluginInstances(
com.google.cloud.apihub.v1.PluginInstance.Builder builderForValue) {
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
pluginInstances_.add(builderForValue.build());
onChanged();
} else {
pluginInstancesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder addPluginInstances(
int index, com.google.cloud.apihub.v1.PluginInstance.Builder builderForValue) {
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
pluginInstances_.add(index, builderForValue.build());
onChanged();
} else {
pluginInstancesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder addAllPluginInstances(
java.lang.Iterable<? extends com.google.cloud.apihub.v1.PluginInstance> values) {
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, pluginInstances_);
onChanged();
} else {
pluginInstancesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder clearPluginInstances() {
if (pluginInstancesBuilder_ == null) {
pluginInstances_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
pluginInstancesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public Builder removePluginInstances(int index) {
if (pluginInstancesBuilder_ == null) {
ensurePluginInstancesIsMutable();
pluginInstances_.remove(index);
onChanged();
} else {
pluginInstancesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public com.google.cloud.apihub.v1.PluginInstance.Builder getPluginInstancesBuilder(int index) {
return getPluginInstancesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public com.google.cloud.apihub.v1.PluginInstanceOrBuilder getPluginInstancesOrBuilder(
int index) {
if (pluginInstancesBuilder_ == null) {
return pluginInstances_.get(index);
} else {
return pluginInstancesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public java.util.List<? extends com.google.cloud.apihub.v1.PluginInstanceOrBuilder>
getPluginInstancesOrBuilderList() {
if (pluginInstancesBuilder_ != null) {
return pluginInstancesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(pluginInstances_);
}
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public com.google.cloud.apihub.v1.PluginInstance.Builder addPluginInstancesBuilder() {
return getPluginInstancesFieldBuilder()
.addBuilder(com.google.cloud.apihub.v1.PluginInstance.getDefaultInstance());
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public com.google.cloud.apihub.v1.PluginInstance.Builder addPluginInstancesBuilder(int index) {
return getPluginInstancesFieldBuilder()
.addBuilder(index, com.google.cloud.apihub.v1.PluginInstance.getDefaultInstance());
}
/**
*
*
* <pre>
* The plugin instances from the specified parent resource.
* </pre>
*
* <code>repeated .google.cloud.apihub.v1.PluginInstance plugin_instances = 1;</code>
*/
public java.util.List<com.google.cloud.apihub.v1.PluginInstance.Builder>
getPluginInstancesBuilderList() {
return getPluginInstancesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apihub.v1.PluginInstance,
com.google.cloud.apihub.v1.PluginInstance.Builder,
com.google.cloud.apihub.v1.PluginInstanceOrBuilder>
getPluginInstancesFieldBuilder() {
if (pluginInstancesBuilder_ == null) {
pluginInstancesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apihub.v1.PluginInstance,
com.google.cloud.apihub.v1.PluginInstance.Builder,
com.google.cloud.apihub.v1.PluginInstanceOrBuilder>(
pluginInstances_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
pluginInstances_ = null;
}
return pluginInstancesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.apihub.v1.ListPluginInstancesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.apihub.v1.ListPluginInstancesResponse)
private static final com.google.cloud.apihub.v1.ListPluginInstancesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apihub.v1.ListPluginInstancesResponse();
}
public static com.google.cloud.apihub.v1.ListPluginInstancesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListPluginInstancesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListPluginInstancesResponse>() {
@java.lang.Override
public ListPluginInstancesResponse 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<ListPluginInstancesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListPluginInstancesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apihub.v1.ListPluginInstancesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,290 | java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/InterconnectAttachmentsStubSettings.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import static com.google.cloud.compute.v1.InterconnectAttachmentsClient.AggregatedListPagedResponse;
import static com.google.cloud.compute.v1.InterconnectAttachmentsClient.ListPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.httpjson.ProtoOperationTransformers;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.AggregatedListInterconnectAttachmentsRequest;
import com.google.cloud.compute.v1.DeleteInterconnectAttachmentRequest;
import com.google.cloud.compute.v1.GetInterconnectAttachmentRequest;
import com.google.cloud.compute.v1.InsertInterconnectAttachmentRequest;
import com.google.cloud.compute.v1.InterconnectAttachment;
import com.google.cloud.compute.v1.InterconnectAttachmentAggregatedList;
import com.google.cloud.compute.v1.InterconnectAttachmentList;
import com.google.cloud.compute.v1.InterconnectAttachmentsScopedList;
import com.google.cloud.compute.v1.ListInterconnectAttachmentsRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.PatchInterconnectAttachmentRequest;
import com.google.cloud.compute.v1.SetLabelsInterconnectAttachmentRequest;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link InterconnectAttachmentsStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (compute.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of get:
*
* <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
* InterconnectAttachmentsStubSettings.Builder interconnectAttachmentsSettingsBuilder =
* InterconnectAttachmentsStubSettings.newBuilder();
* interconnectAttachmentsSettingsBuilder
* .getSettings()
* .setRetrySettings(
* interconnectAttachmentsSettingsBuilder
* .getSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* InterconnectAttachmentsStubSettings interconnectAttachmentsSettings =
* interconnectAttachmentsSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for delete:
*
* <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
* InterconnectAttachmentsStubSettings.Builder interconnectAttachmentsSettingsBuilder =
* InterconnectAttachmentsStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* interconnectAttachmentsSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class InterconnectAttachmentsStubSettings
extends StubSettings<InterconnectAttachmentsStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/compute")
.add("https://www.googleapis.com/auth/cloud-platform")
.build();
private final PagedCallSettings<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings;
private final UnaryCallSettings<DeleteInterconnectAttachmentRequest, Operation> deleteSettings;
private final OperationCallSettings<DeleteInterconnectAttachmentRequest, Operation, Operation>
deleteOperationSettings;
private final UnaryCallSettings<GetInterconnectAttachmentRequest, InterconnectAttachment>
getSettings;
private final UnaryCallSettings<InsertInterconnectAttachmentRequest, Operation> insertSettings;
private final OperationCallSettings<InsertInterconnectAttachmentRequest, Operation, Operation>
insertOperationSettings;
private final PagedCallSettings<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>
listSettings;
private final UnaryCallSettings<PatchInterconnectAttachmentRequest, Operation> patchSettings;
private final OperationCallSettings<PatchInterconnectAttachmentRequest, Operation, Operation>
patchOperationSettings;
private final UnaryCallSettings<SetLabelsInterconnectAttachmentRequest, Operation>
setLabelsSettings;
private final OperationCallSettings<SetLabelsInterconnectAttachmentRequest, Operation, Operation>
setLabelsOperationSettings;
private static final PagedListDescriptor<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
Map.Entry<String, InterconnectAttachmentsScopedList>>
AGGREGATED_LIST_PAGE_STR_DESC =
new PagedListDescriptor<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
Map.Entry<String, InterconnectAttachmentsScopedList>>() {
@Override
public String emptyToken() {
return "";
}
@Override
public AggregatedListInterconnectAttachmentsRequest injectToken(
AggregatedListInterconnectAttachmentsRequest payload, String token) {
return AggregatedListInterconnectAttachmentsRequest.newBuilder(payload)
.setPageToken(token)
.build();
}
@Override
public AggregatedListInterconnectAttachmentsRequest injectPageSize(
AggregatedListInterconnectAttachmentsRequest payload, int pageSize) {
return AggregatedListInterconnectAttachmentsRequest.newBuilder(payload)
.setMaxResults(pageSize)
.build();
}
@Override
public Integer extractPageSize(AggregatedListInterconnectAttachmentsRequest payload) {
return payload.getMaxResults();
}
@Override
public String extractNextToken(InterconnectAttachmentAggregatedList payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Map.Entry<String, InterconnectAttachmentsScopedList>> extractResources(
InterconnectAttachmentAggregatedList payload) {
return payload.getItemsMap().entrySet();
}
};
private static final PagedListDescriptor<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, InterconnectAttachment>
LIST_PAGE_STR_DESC =
new PagedListDescriptor<
ListInterconnectAttachmentsRequest,
InterconnectAttachmentList,
InterconnectAttachment>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListInterconnectAttachmentsRequest injectToken(
ListInterconnectAttachmentsRequest payload, String token) {
return ListInterconnectAttachmentsRequest.newBuilder(payload)
.setPageToken(token)
.build();
}
@Override
public ListInterconnectAttachmentsRequest injectPageSize(
ListInterconnectAttachmentsRequest payload, int pageSize) {
return ListInterconnectAttachmentsRequest.newBuilder(payload)
.setMaxResults(pageSize)
.build();
}
@Override
public Integer extractPageSize(ListInterconnectAttachmentsRequest payload) {
return payload.getMaxResults();
}
@Override
public String extractNextToken(InterconnectAttachmentList payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<InterconnectAttachment> extractResources(
InterconnectAttachmentList payload) {
return payload.getItemsList();
}
};
private static final PagedListResponseFactory<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>
AGGREGATED_LIST_PAGE_STR_FACT =
new PagedListResponseFactory<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>() {
@Override
public ApiFuture<AggregatedListPagedResponse> getFuturePagedResponse(
UnaryCallable<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList>
callable,
AggregatedListInterconnectAttachmentsRequest request,
ApiCallContext context,
ApiFuture<InterconnectAttachmentAggregatedList> futureResponse) {
PageContext<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
Map.Entry<String, InterconnectAttachmentsScopedList>>
pageContext =
PageContext.create(callable, AGGREGATED_LIST_PAGE_STR_DESC, request, context);
return AggregatedListPagedResponse.createAsync(pageContext, futureResponse);
}
};
private static final PagedListResponseFactory<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>
LIST_PAGE_STR_FACT =
new PagedListResponseFactory<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>() {
@Override
public ApiFuture<ListPagedResponse> getFuturePagedResponse(
UnaryCallable<ListInterconnectAttachmentsRequest, InterconnectAttachmentList>
callable,
ListInterconnectAttachmentsRequest request,
ApiCallContext context,
ApiFuture<InterconnectAttachmentList> futureResponse) {
PageContext<
ListInterconnectAttachmentsRequest,
InterconnectAttachmentList,
InterconnectAttachment>
pageContext = PageContext.create(callable, LIST_PAGE_STR_DESC, request, context);
return ListPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to aggregatedList. */
public PagedCallSettings<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings() {
return aggregatedListSettings;
}
/** Returns the object with the settings used for calls to delete. */
public UnaryCallSettings<DeleteInterconnectAttachmentRequest, Operation> deleteSettings() {
return deleteSettings;
}
/** Returns the object with the settings used for calls to delete. */
public OperationCallSettings<DeleteInterconnectAttachmentRequest, Operation, Operation>
deleteOperationSettings() {
return deleteOperationSettings;
}
/** Returns the object with the settings used for calls to get. */
public UnaryCallSettings<GetInterconnectAttachmentRequest, InterconnectAttachment> getSettings() {
return getSettings;
}
/** Returns the object with the settings used for calls to insert. */
public UnaryCallSettings<InsertInterconnectAttachmentRequest, Operation> insertSettings() {
return insertSettings;
}
/** Returns the object with the settings used for calls to insert. */
public OperationCallSettings<InsertInterconnectAttachmentRequest, Operation, Operation>
insertOperationSettings() {
return insertOperationSettings;
}
/** Returns the object with the settings used for calls to list. */
public PagedCallSettings<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>
listSettings() {
return listSettings;
}
/** Returns the object with the settings used for calls to patch. */
public UnaryCallSettings<PatchInterconnectAttachmentRequest, Operation> patchSettings() {
return patchSettings;
}
/** Returns the object with the settings used for calls to patch. */
public OperationCallSettings<PatchInterconnectAttachmentRequest, Operation, Operation>
patchOperationSettings() {
return patchOperationSettings;
}
/** Returns the object with the settings used for calls to setLabels. */
public UnaryCallSettings<SetLabelsInterconnectAttachmentRequest, Operation> setLabelsSettings() {
return setLabelsSettings;
}
/** Returns the object with the settings used for calls to setLabels. */
public OperationCallSettings<SetLabelsInterconnectAttachmentRequest, Operation, Operation>
setLabelsOperationSettings() {
return setLabelsOperationSettings;
}
public InterconnectAttachmentsStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonInterconnectAttachmentsStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "compute";
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
@ObsoleteApi("Use getEndpoint() instead")
public static String getDefaultEndpoint() {
return "compute.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "compute.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultHttpJsonTransportProviderBuilder().build();
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(InterconnectAttachmentsStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected InterconnectAttachmentsStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
aggregatedListSettings = settingsBuilder.aggregatedListSettings().build();
deleteSettings = settingsBuilder.deleteSettings().build();
deleteOperationSettings = settingsBuilder.deleteOperationSettings().build();
getSettings = settingsBuilder.getSettings().build();
insertSettings = settingsBuilder.insertSettings().build();
insertOperationSettings = settingsBuilder.insertOperationSettings().build();
listSettings = settingsBuilder.listSettings().build();
patchSettings = settingsBuilder.patchSettings().build();
patchOperationSettings = settingsBuilder.patchOperationSettings().build();
setLabelsSettings = settingsBuilder.setLabelsSettings().build();
setLabelsOperationSettings = settingsBuilder.setLabelsOperationSettings().build();
}
/** Builder for InterconnectAttachmentsStubSettings. */
public static class Builder
extends StubSettings.Builder<InterconnectAttachmentsStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings;
private final UnaryCallSettings.Builder<DeleteInterconnectAttachmentRequest, Operation>
deleteSettings;
private final OperationCallSettings.Builder<
DeleteInterconnectAttachmentRequest, Operation, Operation>
deleteOperationSettings;
private final UnaryCallSettings.Builder<
GetInterconnectAttachmentRequest, InterconnectAttachment>
getSettings;
private final UnaryCallSettings.Builder<InsertInterconnectAttachmentRequest, Operation>
insertSettings;
private final OperationCallSettings.Builder<
InsertInterconnectAttachmentRequest, Operation, Operation>
insertOperationSettings;
private final PagedCallSettings.Builder<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>
listSettings;
private final UnaryCallSettings.Builder<PatchInterconnectAttachmentRequest, Operation>
patchSettings;
private final OperationCallSettings.Builder<
PatchInterconnectAttachmentRequest, Operation, Operation>
patchOperationSettings;
private final UnaryCallSettings.Builder<SetLabelsInterconnectAttachmentRequest, Operation>
setLabelsSettings;
private final OperationCallSettings.Builder<
SetLabelsInterconnectAttachmentRequest, Operation, Operation>
setLabelsOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(600000L))
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build();
definitions.put("retry_policy_0_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(600000L))
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build();
definitions.put("no_retry_1_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
aggregatedListSettings = PagedCallSettings.newBuilder(AGGREGATED_LIST_PAGE_STR_FACT);
deleteSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteOperationSettings = OperationCallSettings.newBuilder();
getSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
insertSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
insertOperationSettings = OperationCallSettings.newBuilder();
listSettings = PagedCallSettings.newBuilder(LIST_PAGE_STR_FACT);
patchSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
patchOperationSettings = OperationCallSettings.newBuilder();
setLabelsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
setLabelsOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
aggregatedListSettings,
deleteSettings,
getSettings,
insertSettings,
listSettings,
patchSettings,
setLabelsSettings);
initDefaults(this);
}
protected Builder(InterconnectAttachmentsStubSettings settings) {
super(settings);
aggregatedListSettings = settings.aggregatedListSettings.toBuilder();
deleteSettings = settings.deleteSettings.toBuilder();
deleteOperationSettings = settings.deleteOperationSettings.toBuilder();
getSettings = settings.getSettings.toBuilder();
insertSettings = settings.insertSettings.toBuilder();
insertOperationSettings = settings.insertOperationSettings.toBuilder();
listSettings = settings.listSettings.toBuilder();
patchSettings = settings.patchSettings.toBuilder();
patchOperationSettings = settings.patchOperationSettings.toBuilder();
setLabelsSettings = settings.setLabelsSettings.toBuilder();
setLabelsOperationSettings = settings.setLabelsOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
aggregatedListSettings,
deleteSettings,
getSettings,
insertSettings,
listSettings,
patchSettings,
setLabelsSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.aggregatedListSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.deleteSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.insertSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.listSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.patchSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.setLabelsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.deleteOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteInterconnectAttachmentRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.insertOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<InsertInterconnectAttachmentRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.patchOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<PatchInterconnectAttachmentRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
builder
.setLabelsOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<SetLabelsInterconnectAttachmentRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(Operation.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(Operation.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(500L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(20000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(600000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to aggregatedList. */
public PagedCallSettings.Builder<
AggregatedListInterconnectAttachmentsRequest,
InterconnectAttachmentAggregatedList,
AggregatedListPagedResponse>
aggregatedListSettings() {
return aggregatedListSettings;
}
/** Returns the builder for the settings used for calls to delete. */
public UnaryCallSettings.Builder<DeleteInterconnectAttachmentRequest, Operation>
deleteSettings() {
return deleteSettings;
}
/** Returns the builder for the settings used for calls to delete. */
public OperationCallSettings.Builder<DeleteInterconnectAttachmentRequest, Operation, Operation>
deleteOperationSettings() {
return deleteOperationSettings;
}
/** Returns the builder for the settings used for calls to get. */
public UnaryCallSettings.Builder<GetInterconnectAttachmentRequest, InterconnectAttachment>
getSettings() {
return getSettings;
}
/** Returns the builder for the settings used for calls to insert. */
public UnaryCallSettings.Builder<InsertInterconnectAttachmentRequest, Operation>
insertSettings() {
return insertSettings;
}
/** Returns the builder for the settings used for calls to insert. */
public OperationCallSettings.Builder<InsertInterconnectAttachmentRequest, Operation, Operation>
insertOperationSettings() {
return insertOperationSettings;
}
/** Returns the builder for the settings used for calls to list. */
public PagedCallSettings.Builder<
ListInterconnectAttachmentsRequest, InterconnectAttachmentList, ListPagedResponse>
listSettings() {
return listSettings;
}
/** Returns the builder for the settings used for calls to patch. */
public UnaryCallSettings.Builder<PatchInterconnectAttachmentRequest, Operation>
patchSettings() {
return patchSettings;
}
/** Returns the builder for the settings used for calls to patch. */
public OperationCallSettings.Builder<PatchInterconnectAttachmentRequest, Operation, Operation>
patchOperationSettings() {
return patchOperationSettings;
}
/** Returns the builder for the settings used for calls to setLabels. */
public UnaryCallSettings.Builder<SetLabelsInterconnectAttachmentRequest, Operation>
setLabelsSettings() {
return setLabelsSettings;
}
/** Returns the builder for the settings used for calls to setLabels. */
public OperationCallSettings.Builder<
SetLabelsInterconnectAttachmentRequest, Operation, Operation>
setLabelsOperationSettings() {
return setLabelsOperationSettings;
}
@Override
public InterconnectAttachmentsStubSettings build() throws IOException {
return new InterconnectAttachmentsStubSettings(this);
}
}
}
|
googleapis/google-cloud-java | 38,144 | java-translate/proto-google-cloud-translate-v3beta1/src/main/java/com/google/cloud/translate/v3beta1/GlossaryInputConfig.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/translate/v3beta1/translation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3beta1;
/**
*
*
* <pre>
* Input configuration for glossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3beta1.GlossaryInputConfig}
*/
public final class GlossaryInputConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3beta1.GlossaryInputConfig)
GlossaryInputConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use GlossaryInputConfig.newBuilder() to construct.
private GlossaryInputConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GlossaryInputConfig() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GlossaryInputConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_GlossaryInputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_GlossaryInputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3beta1.GlossaryInputConfig.class,
com.google.cloud.translate.v3beta1.GlossaryInputConfig.Builder.class);
}
private int sourceCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object source_;
public enum SourceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
GCS_SOURCE(1),
SOURCE_NOT_SET(0);
private final int value;
private SourceCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SourceCase valueOf(int value) {
return forNumber(value);
}
public static SourceCase forNumber(int value) {
switch (value) {
case 1:
return GCS_SOURCE;
case 0:
return SOURCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public static final int GCS_SOURCE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.GcsSource getGcsSource() {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3beta1.GcsSource) source_;
}
return com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3beta1.GcsSource) source_;
}
return com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (sourceCase_ == 1) {
output.writeMessage(1, (com.google.cloud.translate.v3beta1.GcsSource) source_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sourceCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.translate.v3beta1.GcsSource) source_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.translate.v3beta1.GlossaryInputConfig)) {
return super.equals(obj);
}
com.google.cloud.translate.v3beta1.GlossaryInputConfig other =
(com.google.cloud.translate.v3beta1.GlossaryInputConfig) obj;
if (!getSourceCase().equals(other.getSourceCase())) return false;
switch (sourceCase_) {
case 1:
if (!getGcsSource().equals(other.getGcsSource())) return false;
break;
case 0:
default:
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
switch (sourceCase_) {
case 1:
hash = (37 * hash) + GCS_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGcsSource().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.translate.v3beta1.GlossaryInputConfig prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Input configuration for glossaries.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3beta1.GlossaryInputConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3beta1.GlossaryInputConfig)
com.google.cloud.translate.v3beta1.GlossaryInputConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_GlossaryInputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_GlossaryInputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3beta1.GlossaryInputConfig.class,
com.google.cloud.translate.v3beta1.GlossaryInputConfig.Builder.class);
}
// Construct using com.google.cloud.translate.v3beta1.GlossaryInputConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (gcsSourceBuilder_ != null) {
gcsSourceBuilder_.clear();
}
sourceCase_ = 0;
source_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3beta1.TranslationServiceProto
.internal_static_google_cloud_translation_v3beta1_GlossaryInputConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.GlossaryInputConfig getDefaultInstanceForType() {
return com.google.cloud.translate.v3beta1.GlossaryInputConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.GlossaryInputConfig build() {
com.google.cloud.translate.v3beta1.GlossaryInputConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.GlossaryInputConfig buildPartial() {
com.google.cloud.translate.v3beta1.GlossaryInputConfig result =
new com.google.cloud.translate.v3beta1.GlossaryInputConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.translate.v3beta1.GlossaryInputConfig result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.translate.v3beta1.GlossaryInputConfig result) {
result.sourceCase_ = sourceCase_;
result.source_ = this.source_;
if (sourceCase_ == 1 && gcsSourceBuilder_ != null) {
result.source_ = gcsSourceBuilder_.build();
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.translate.v3beta1.GlossaryInputConfig) {
return mergeFrom((com.google.cloud.translate.v3beta1.GlossaryInputConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3beta1.GlossaryInputConfig other) {
if (other == com.google.cloud.translate.v3beta1.GlossaryInputConfig.getDefaultInstance())
return this;
switch (other.getSourceCase()) {
case GCS_SOURCE:
{
mergeGcsSource(other.getGcsSource());
break;
}
case SOURCE_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getGcsSourceFieldBuilder().getBuilder(), extensionRegistry);
sourceCase_ = 1;
break;
} // case 10
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int sourceCase_ = 0;
private java.lang.Object source_;
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public Builder clearSource() {
sourceCase_ = 0;
source_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3beta1.GcsSource,
com.google.cloud.translate.v3beta1.GcsSource.Builder,
com.google.cloud.translate.v3beta1.GcsSourceOrBuilder>
gcsSourceBuilder_;
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.GcsSource getGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3beta1.GcsSource) source_;
}
return com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
} else {
if (sourceCase_ == 1) {
return gcsSourceBuilder_.getMessage();
}
return com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(com.google.cloud.translate.v3beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
} else {
gcsSourceBuilder_.setMessage(value);
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(
com.google.cloud.translate.v3beta1.GcsSource.Builder builderForValue) {
if (gcsSourceBuilder_ == null) {
source_ = builderForValue.build();
onChanged();
} else {
gcsSourceBuilder_.setMessage(builderForValue.build());
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
public Builder mergeGcsSource(com.google.cloud.translate.v3beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1
&& source_ != com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance()) {
source_ =
com.google.cloud.translate.v3beta1.GcsSource.newBuilder(
(com.google.cloud.translate.v3beta1.GcsSource) source_)
.mergeFrom(value)
.buildPartial();
} else {
source_ = value;
}
onChanged();
} else {
if (sourceCase_ == 1) {
gcsSourceBuilder_.mergeFrom(value);
} else {
gcsSourceBuilder_.setMessage(value);
}
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
public Builder clearGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
onChanged();
}
} else {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
}
gcsSourceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
public com.google.cloud.translate.v3beta1.GcsSource.Builder getGcsSourceBuilder() {
return getGcsSourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if ((sourceCase_ == 1) && (gcsSourceBuilder_ != null)) {
return gcsSourceBuilder_.getMessageOrBuilder();
} else {
if (sourceCase_ == 1) {
return (com.google.cloud.translate.v3beta1.GcsSource) source_;
}
return com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Required. Google Cloud Storage location of glossary data.
* File format is determined based on the filename extension. API returns
* [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file
* formats. Wildcards are not allowed. This must be a single file in one of
* the following formats:
*
* For unidirectional glossaries:
*
* - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated.
* The first column is source text. The second column is target text.
* The file must not contain headers. That is, the first row is data, not
* column names.
*
* - TMX (`.tmx`): TMX file with parallel data defining source/target term
* pairs.
*
* For equivalent term sets glossaries:
*
* - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms
* in multiple languages. See documentation for more information -
* [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
* </pre>
*
* <code>.google.cloud.translation.v3beta1.GcsSource gcs_source = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3beta1.GcsSource,
com.google.cloud.translate.v3beta1.GcsSource.Builder,
com.google.cloud.translate.v3beta1.GcsSourceOrBuilder>
getGcsSourceFieldBuilder() {
if (gcsSourceBuilder_ == null) {
if (!(sourceCase_ == 1)) {
source_ = com.google.cloud.translate.v3beta1.GcsSource.getDefaultInstance();
}
gcsSourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.translate.v3beta1.GcsSource,
com.google.cloud.translate.v3beta1.GcsSource.Builder,
com.google.cloud.translate.v3beta1.GcsSourceOrBuilder>(
(com.google.cloud.translate.v3beta1.GcsSource) source_,
getParentForChildren(),
isClean());
source_ = null;
}
sourceCase_ = 1;
onChanged();
return gcsSourceBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.translation.v3beta1.GlossaryInputConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3beta1.GlossaryInputConfig)
private static final com.google.cloud.translate.v3beta1.GlossaryInputConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3beta1.GlossaryInputConfig();
}
public static com.google.cloud.translate.v3beta1.GlossaryInputConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GlossaryInputConfig> PARSER =
new com.google.protobuf.AbstractParser<GlossaryInputConfig>() {
@java.lang.Override
public GlossaryInputConfig parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<GlossaryInputConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GlossaryInputConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3beta1.GlossaryInputConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/nosql | 38,149 | kvmain/src/main/java/oracle/kv/impl/rep/table/SecondaryInfoMap.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.rep.table;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import oracle.kv.KVVersion;
import oracle.kv.impl.api.table.FieldComparator;
import oracle.kv.impl.api.table.IndexImpl;
import oracle.kv.impl.api.table.NameUtils;
import oracle.kv.impl.api.table.TableImpl;
import oracle.kv.impl.api.table.TableKey;
import oracle.kv.impl.api.table.TableMetadata;
import oracle.kv.impl.metadata.Metadata;
import oracle.kv.impl.test.TestHookExecute;
import oracle.kv.impl.topo.PartitionId;
import oracle.kv.impl.util.DatabaseUtils;
import oracle.kv.impl.util.SerializationUtil;
import oracle.kv.impl.util.TxnUtil;
import oracle.kv.table.PrimaryKey;
import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseNotFoundException;
import com.sleepycat.je.Durability;
import com.sleepycat.je.Durability.ReplicaAckPolicy;
import com.sleepycat.je.Durability.SyncPolicy;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionConfig;
import com.sleepycat.je.rep.NoConsistencyRequiredPolicy;
import com.sleepycat.je.rep.ReplicatedEnvironment;
/**
* Persistent class containing information on populating secondary databases
* as well as information on tables that have been deleted and need
* cleaning. This information is used by MaintenanceThread instances to perform
* cleaning tasks.
*
* A single instance of this object is kept in a replicated database for use
* by the master of the shard.
*
* There is a single record, keyed by the (String) constant:
* SECONDARY_INFO_KEY
*
* The record data is serialized byte array of the class instance. The instance
* contains 2 major components:
* 1. Map of String to SecondaryInfo, used to track population of new indexes.
* key: the database name of the secondary (index) database
* value: serialized SecondaryInfo
* 2. Map of String to DeletedTableInfo to track background removal of records
* from deleted tables.
* key: the full table name. If namespaces are used, namespace:table_name
* value: serialized DeletedTableInfo
*
* Because this class is stored as a singleton it's important to be sure that
* updates are single-threaded or otherwise synchronized. At this time access
* is single-threaded because there is only a single thread accessing the
* data at one time.
*
* Note that earlier code used HashMap for secondayMap and deletedTableMap.
* This caused issues since table and index names are case-insensitive. The
* maps were changed to TreeMap with a case-insensitive comparator in 4.4. The
* version was not bumped to avoid shard upgrade issues. The comparator class,
* FieldComparator was introduced at the same time this class so there are
* no issues deserializing a the new instance by old code.
*/
class SecondaryInfoMap implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SECONDARY_INFO_KEY = "SecondaryInfoMap";
private static final DatabaseEntry secondaryInfoKey = new DatabaseEntry();
static {
StringBinding.stringToEntry(SECONDARY_INFO_KEY, secondaryInfoKey);
}
/*
* Transaction configuration for r/w secondary info.
*
* <p>Read-committed is used to avoid holding read locks unnecessarily
* during a populateSecondaries scan. For other operations (all updates)
* this has no impact since LockMode.RMW is always used.</p>
*/
static final TransactionConfig SECONDARY_INFO_CONFIG =
new TransactionConfig().
setReadCommitted(true).
setConsistencyPolicy(NoConsistencyRequiredPolicy.NO_CONSISTENCY).
setDurability(
new Durability(Durability.SyncPolicy.SYNC,
Durability.SyncPolicy.SYNC,
Durability.ReplicaAckPolicy.SIMPLE_MAJORITY));
/*
* Transaction configuration for secondary cleaner operations. Cleaner
* operations can have looser durability to improve performance since any
* lost deletes would be retried when the cleaner was restarted during
* recovery.
*/
static final TransactionConfig CLEANER_CONFIG =
new TransactionConfig().
setConsistencyPolicy(NoConsistencyRequiredPolicy.NO_CONSISTENCY).
setDurability(
new Durability(Durability.SyncPolicy.NO_SYNC,
Durability.SyncPolicy.NO_SYNC,
Durability.ReplicaAckPolicy.SIMPLE_MAJORITY));
/*
* Transaction config to return what is locally at the replica, without
* waiting for the master to make the state consistent wrt the master.
* Also, the transaction will not wait for commit acks from the replicas.
*/
private static final TransactionConfig NO_WAIT_CONFIG =
new TransactionConfig().
setDurability(new Durability(SyncPolicy.NO_SYNC,
SyncPolicy.NO_SYNC,
ReplicaAckPolicy.NONE)).
setConsistencyPolicy(NoConsistencyRequiredPolicy.NO_CONSISTENCY);
/* Current schema version. See note below about changing the version. */
private static final int CURRENT_SCHEMA_VERSION = 1;
/*
* Maps secondary DB name -> SecondaryInfo. Used for index population
* and index cleaning on partition migration.
*/
private Map<String, SecondaryInfo> secondaryMap =
new TreeMap<>(FieldComparator.instance);
/*
* Maps table name -> deleted table info. This map contains entries for
* the tables which have been deleted and their data removed.
* The String name is a namespace-qualified table name:
* [namespace:]fullTableName
*/
private Map<String, DeletedTableInfo> deletedTableMap =
new TreeMap<>(FieldComparator.instance);
/*
* The table metadata seq. number that the data is this object is based on.
*/
private int metadataSequenceNum = Metadata.EMPTY_SEQUENCE_NUMBER;
/*
* Version of this object. In order to change the schema version, all nodes
* in the shard must first be upgraded to software that supports the new
* schema.
*/
private final int version;
private SecondaryInfoMap() {
version = CURRENT_SCHEMA_VERSION;
}
/**
* Gets the last seen metadata sequence number.
*
* @return the last seen metadata sequence number
*/
int getMetadataSequenceNum() {
return metadataSequenceNum;
}
/**
* Sets the last seen metadata sequence number.
*
* @param seqNum
*/
void setMetadataSequenceNum(int seqNum) {
assert seqNum >= metadataSequenceNum;
metadataSequenceNum = seqNum;
}
/**
* Adds an info record for the specified secondary database if it isn't
* already there.
*
* @param dbName the secondary database name
* @param db the secondary info database
* @param txn a transaction
* @param logger
*/
static void add(String dbName, Database db,
Transaction txn, Logger logger) {
final SecondaryInfoMap infoMap = fetch(db, txn, LockMode.RMW);
SecondaryInfo info = infoMap.secondaryMap.get(dbName);
if (info == null) {
info = new SecondaryInfo();
infoMap.secondaryMap.put(dbName, info);
logger.log(Level.FINE, "Adding {0} for {1}, map size= {2}",
new Object[]{info, dbName,
infoMap.secondaryMap.size()});
infoMap.persist(db, txn);
}
}
/**
* Updates the secondary info map. Checks to see if an index has been
* removed and record deleted tables if needed. If an index has been
* removed the secondary DB for that index is removed. This method is
* called from the table maintenance thread.
*/
static void update(TableMetadata tableMetadata,
Map<String, IndexImpl> indexes,
Set<TableImpl> deletedTables,
MaintenanceThread maintenanceThread,
Database infoDb,
ReplicatedEnvironment repEnv,
Logger logger) {
assert infoDb != null;
Transaction txn = null;
try {
boolean modified = false;
txn = repEnv.beginTransaction(null, SECONDARY_INFO_CONFIG);
final SecondaryInfoMap infoMap = fetch(infoDb, txn, LockMode.RMW);
final Iterator<Entry<String, SecondaryInfo>> itr =
infoMap.secondaryMap.entrySet().iterator();
/* Remove secondary info for indexes that have been dropped */
while (itr.hasNext()) {
if (maintenanceThread.isStopped()) {
return;
}
final Entry<String, SecondaryInfo> entry = itr.next();
final String dbName = entry.getKey();
if (!indexes.containsKey(dbName)) {
/*
* The DB must be closed before removing it. If the close
* fails skip it, to be retried again.
*/
if (!maintenanceThread.closeSecondary(dbName)) {
logger.log(Level.INFO,
"Skiping removing secondary database {0}",
dbName);
continue;
}
logger.log(Level.INFO, "Removing secondary database {0}",
dbName);
try {
assert TestHookExecute.
doHookIfSet(TableManager.BEFORE_REMOVE_HOOK, 1);
logger.log(Level.FINE,
"Secondary database {0} is not " +
"defined in table metadata " +
"seq# {1} and is being removed.",
new Object[]{dbName,
tableMetadata.
getSequenceNumber()});
/*
* Mark the secondary removed, then attempt to remove
* the DB. If the remove fails, marking it will keep
* it from being used until the DB is sucessfully
* removed during some future check.
*/
entry.getValue().setRemoved();
modified = true;
/* Actually remove the DB */
repEnv.removeDatabase(txn, dbName);
/* Remove the associated SecondaryInfo instance */
itr.remove();
} catch (DatabaseNotFoundException ignore) {
/* Already gone */
itr.remove();
} catch (RuntimeException re) {
/*
* Log the exception and go on, leaving the db info in
* the map for next time.
*/
logger.log(Level.INFO,
"Exception removing {0}: {1}, operation " +
"will be retried",
new Object[]{dbName, re.getMessage()});
} finally {
assert TestHookExecute.
doHookIfSet(TableManager.AFTER_REMOVE_HOOK, 1);
}
}
}
final Iterator<Entry<String, DeletedTableInfo>> itr2 =
infoMap.deletedTableMap.entrySet().iterator();
/*
* Remove deleted table info for tables which have been removed
* from the metadata.
*/
while (itr2.hasNext()) {
if (maintenanceThread.isStopped()) {
return;
}
final Entry<String, DeletedTableInfo> entry = itr2.next();
final String name = entry.getKey();
final DeletedTableInfo info = entry.getValue();
final String namespace =
NameUtils.getNamespaceFromQualifiedName(name);
final String tableName =
NameUtils.getFullNameFromQualifiedName(name);
final TableImpl table =
tableMetadata.getTable(namespace, tableName);
/*
* If the table is gone, clean out the info. Note that a new
* table with the same name may show up before the info for
* the old table is removed. In that case the new table will
* have a different ID.
*/
if ((table == null) ||
(table.getId() != info.getTargetTableId())) {
assert info.isDone() : name + " : " + info.toString();
itr2.remove();
modified = true;
} else {
/* Still in the MD, make sure it was marked for delete */
if (!table.getStatus().isDeleting()) {
/*
* We think the table is being deleted, yet the MD
* says the table is valid (not being deleted). So
* something very bad happened.
*
* TODO - Work needs to be done to determine causes
* and remedies.
*/
logger.log(Level.SEVERE,
"Table metadata {0} includes table {1} but" +
" node thinks the table is deleted",
new Object[]{tableMetadata.getSequenceNumber(),
table});
}
}
}
/* Add entries for tables marked for delete */
for (TableImpl table : deletedTables) {
if (maintenanceThread.isStopped()) {
return;
}
final String tableName = table.getFullNamespaceName();
final DeletedTableInfo info =
infoMap.getDeletedTableInfo(tableName);
if (info == null) {
infoMap.deletedTableMap.put(tableName,
new DeletedTableInfo(table));
modified = true;
}
}
if (modified) {
try {
infoMap.persist(infoDb, txn);
txn.commit();
txn = null;
} catch (RuntimeException re) {
DatabaseUtils.handleException(re, logger,
"populate info map");
}
}
} finally {
TxnUtil.abort(txn);
}
}
static void markForSecondaryCleaning(Database db, Logger logger) {
Transaction txn = null;
try {
txn = db.getEnvironment().beginTransaction(null,
SECONDARY_INFO_CONFIG);
final SecondaryInfoMap infoMap = fetch(db, txn, LockMode.RMW);
if (infoMap.secondaryMap.isEmpty()) {
return;
}
logger.log(Level.FINE, "Marking {0} for cleaning",
infoMap.secondaryMap.size());
for (SecondaryInfo info : infoMap.secondaryMap.values()) {
info.markForCleaning();
}
try {
infoMap.persist(db, txn);
txn.commit();
txn = null;
} catch (RuntimeException re) { // TODO - combine trys
DatabaseUtils.handleException(re, logger,
"populate info map");
}
} finally {
if (txn != null) {
txn.abort();
}
}
}
/**
* Fetches the SecondaryInfoMap object from the db for
* read-only use. If the db is empty an empty SecondaryInfoMap is returned.
*
* @param db the secondary info map db
* @return a SecondaryInfoMap object
*/
static SecondaryInfoMap fetch(Database db) {
final Transaction txn = db.getEnvironment().
beginTransaction(null, NO_WAIT_CONFIG);
try {
return fetch(db, txn, LockMode.DEFAULT);
} finally {
/* We are just reading. */
if (txn.isValid()) {
txn.commit();
} else {
TxnUtil.abort(txn);
}
}
}
/**
* Fetches the SecondaryInfoMap object from the db. If the db is empty an
* empty SecondaryInfoMap is returned.
*
* @param db the secondary info map db
* @param txn the transaction to use for the get
* @param lockMode for the get
* @return a SecondaryInfoMap object
*/
static SecondaryInfoMap fetch(Database db,
Transaction txn,
LockMode lockMode) {
if (txn == null) {
throw new IllegalStateException("transaction can not be null");
}
final DatabaseEntry value = new DatabaseEntry();
db.get(txn, secondaryInfoKey, value, lockMode);
final SecondaryInfoMap infoMap =
SerializationUtil.getObject(value.getData(),
SecondaryInfoMap.class);
/* If none, return an empty object */
return (infoMap == null) ? new SecondaryInfoMap() : infoMap;
}
/**
* Persists this object to the db using the specified transaction.
*
* @param db the secondary info map db
* @param txn transaction to use for the write
*/
void persist(Database db, Transaction txn) {
db.put(txn, secondaryInfoKey,
new DatabaseEntry(SerializationUtil.getBytes(this)));
}
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ois.defaultReadObject();
if (version > CURRENT_SCHEMA_VERSION) {
throw new IllegalStateException
("The secondary info map is at " +
KVVersion.CURRENT_VERSION +
", schema version " + CURRENT_SCHEMA_VERSION +
" but the stored schema is at version " + version +
". Please upgrade this node's NoSQL Database version.");
}
/*
* Early code used HashMap for secondaryMap and deletedTableMap. If
* these are detected convert them to TreeMap. Note that we are not
* changing the schema version for this.
*/
if (secondaryMap instanceof HashMap) {
final Map<String, SecondaryInfo> newSecondaryMap =
new TreeMap<>(FieldComparator.instance);
newSecondaryMap.putAll(secondaryMap);
secondaryMap = newSecondaryMap;
}
if (deletedTableMap instanceof HashMap) {
final Map<String, DeletedTableInfo> newDeletedTableMap =
new TreeMap<>(FieldComparator.instance);
newDeletedTableMap.putAll(deletedTableMap);
deletedTableMap = newDeletedTableMap;
}
}
/**
* Gets the secondary info object for the specified db. If none exist
* null is returned.
*/
SecondaryInfo getSecondaryInfo(String dbName) {
final SecondaryInfo info = secondaryMap.get(dbName);
return (info == null) ? null : (info.isRemoved() ? null : info);
}
/**
* Returns true if a secondary DB needs populating.
*/
boolean secondaryNeedsPopulate() {
for (SecondaryInfo info : secondaryMap.values()) {
if (info.needsPopulating()) {
return true;
}
}
return false;
}
/**
* Returns a set of entries for secondaries that need to be populated.
* The iteration order of the set is from least recently populated to
* most recent based on the value set by SecondaryInfo.completePass(long).
*/
Set<Entry<String, SecondaryInfo>> getSecondariesToPopulate() {
final Set<Entry<String, SecondaryInfo>> entries =
new TreeSet<>((Entry<String, SecondaryInfo> o1,
Entry<String, SecondaryInfo> o2) ->
(int)(o1.getValue().lastPass - o2.getValue().lastPass));
for (Entry<String, SecondaryInfo> entry : secondaryMap.entrySet()) {
final SecondaryInfo info = entry.getValue();
if (info.needsPopulating()) {
entries.add(entry);
}
}
return entries;
}
/**
* Returns true if a secondary DB needs cleaning.
*/
boolean secondaryNeedsCleaning() {
return getNextSecondaryToClean() != null;
}
/**
* Gets the next secondary DB to clean. Returns null if no secondaries need
* cleaning.
*/
String getNextSecondaryToClean() {
/*
* Secondary cleaning does not need specical ordering so just return
* the first found.
*/
for (Entry<String, SecondaryInfo> entry : secondaryMap.entrySet()) {
if (entry.getValue().needsCleaning()) {
return entry.getKey();
}
}
return null;
}
/**
* Gets the deleted info object for the specified table if exists. If
* no tables need cleaning null is returned.
*
* tableName is a namespace name ([namespace:]tableName)
*/
DeletedTableInfo getDeletedTableInfo(String tableName) {
return tableName == null ? null : deletedTableMap.get(tableName);
}
/**
* Returns true if a table needs cleaning.
*/
boolean tableNeedCleaning() {
for (DeletedTableInfo info : deletedTableMap.values()) {
if (!info.isDone()) {
return true;
}
}
return false;
}
/**
* Gets the next table to clean. Returns null if there are none.
* If there are multiple tables that need cleaning this method will
* return the least recently cleaned table.
*/
DeletedTableInfo getNextTableToClean() {
DeletedTableInfo ret = null;
for (DeletedTableInfo info : deletedTableMap.values()) {
if (info.isDone()) {
continue;
}
/* Create a roughly round-robin scheme by returning the table
* with the oldest cleaning time. New tables will pop to the
* front for one pass.
*/
if ((ret == null) || (ret.lastPass > info.lastPass)) {
ret = info;
}
}
return ret;
}
/*
* Get the secondaryMap for index information.
*/
public Map<String, SecondaryInfo> getSecondaryMap() {
return this.secondaryMap;
}
/*
* Get the deletedTableMap for deleted table information.
*/
public Map<String, DeletedTableInfo> getDeletedTableMap() {
return this.deletedTableMap;
}
@Override
public String toString() {
return "SecondaryInfoMap[" + secondaryMap.size() + ", " +
deletedTableMap.size() + "]";
}
/*
* Container for information regarding secondary databases which are
* being populated.
*/
static class SecondaryInfo implements Serializable {
private static final long serialVersionUID = 1L;
/* true if the DB needs to be populated */
private boolean needsPopulating = true;
/*
* Count of population attempts. Note: this counter was added at 18.3,
* after the initial release and may be lost during an upgrade. However
* the impact is minimal (the population may just be retried a few
* extra times.
*/
private int populationAttempts = 0;
/* Maxinum number of times we will attempt to populate a secondary. */
private static final int MAX_POPULATE_ATTEMPTS = 10;
/*
* true if the DB needs cleaning. Note that cleaning is disabled until
* the db has been populated.
*/
private boolean needsCleaning = false;
/* The last key used to populate/clean */
private DatabaseEntry lastKey = null;
/* The last data used to clean */
private DatabaseEntry lastData = null;
/* The partition being used to populate */
private PartitionId currentPartition = null;
/* The set of partitions which have been completed */
private Set<PartitionId> completed = null;
/*
* True if the index for this secondary DB has been dropped, but the
* secondary DB has not yet been removed.
*
* Note that this flag was added and therefore may be lost in an
* upgrade situation. However, this is more an optimization and things
* will function property if incorrectly set to false.
*/
private boolean removed = false;
/*
* This is non-null if the maintenance operation fails for some
* reason.
*/
private String errorString = null;
/*
* Time of last of population pass. This field was introduced after the
* initial release but does not need any upgrade consideration. It is
* used for an optimization, and can be lost in a mixed version shard.
*
* Note that this is not used for cleaning.
*/
private long lastPass = 0L;
/*
* Total read and write costs due to secondary population. These
* fields were introduced after the initial release but do not need
* any upgrade consideration. They are for debugging purposes only
* and can be lost in a mixed version shard.
*/
private long totalReadKB = 0L;
private long totalWriteKB = 0L;
/**
* Returns true if the secondary DB needs to be populated.
*
* @return true if the secondary DB needs to be populated
*/
boolean needsPopulating() {
return needsPopulating;
}
/**
* Signal that this secondary DB has been populated.
*/
void donePopulation() {
assert needsPopulating == true;
needsPopulating = false;
clearPopulationParameters();
}
/**
* Sets the needs cleaning flag.
*/
void markForCleaning() {
if (!removed) {
needsCleaning = true;
}
}
/**
* Returns true if the secondary DB needs cleaning. Note that cleaning
* is disabled until population is completed.
*
* @return true if the secondary DB needs cleaning
*/
boolean needsCleaning() {
return needsPopulating ? false : needsCleaning;
}
void doneCleaning() {
assert !needsPopulating;
needsCleaning = false;
lastKey = null;
lastData = null;
}
/**
* Gets the last key set through setLastKey(). If no last key was set,
* then an empty DatabaseEntry object is returned.
*
* @return the last key
*/
DatabaseEntry getLastKey() {
if (lastKey == null) {
lastKey = new DatabaseEntry();
}
return lastKey;
}
DatabaseEntry getLastData() {
assert needsPopulating == false; /* only used for cleaning */
if (lastData == null) {
lastData = new DatabaseEntry();
}
return lastData;
}
/**
* Gets the partition currently being read from.
*
* @return the partition currently being read from or null
*/
PartitionId getCurrentPartition() {
assert needsPopulating == true;
return currentPartition;
}
/**
* Sets the current partition.
*
* @param partitionId
*/
void setCurrentPartition(PartitionId partitionId) {
assert needsPopulating == true;
assert partitionId != null;
assert currentPartition == null;
currentPartition = partitionId;
}
/**
* Returns true if a populate from the specified partition has been
* completed.
*
* @param partitionId
* @return true if a populate has been completed
*/
boolean isCompleted(PartitionId partitionId) {
assert needsPopulating == true;
return completed == null ? false : completed.contains(partitionId);
}
/**
* Completes the current populate. Calling this method will add the
* current partition to the completed list and clear the current
* partition and last key.
*/
void completeCurrentPartition() {
assert needsPopulating == true;
if (completed == null) {
completed = new HashSet<>();
}
completed.add(currentPartition);
currentPartition = null;
lastKey = null;
lastData = null;
}
/*
* Records the time of a population pass.
*/
void completePass(long timeStamp) {
lastPass = timeStamp;
}
/*
* Returns the time in MS since the last pass (since completePlass
* was called).
*/
long msSinceLastPass(long timeStamp) {
return timeStamp - lastPass;
}
/*
* Accumulate read and write throughput.
*/
void accumulateThroughput(int readKB, int writeKB) {
totalReadKB += readKB;
totalWriteKB += writeKB;
}
/*
* Set an error string and cancel any current, or future
* population.
*/
void setErrorString(Exception exception) {
errorString = exception.getClass().getSimpleName() +
" " + exception.getMessage();
needsPopulating = false;
}
String getErrorString() {
return errorString;
}
/**
* Returns true if the remove flag is set.
*
* @return true if the remove flag is set
*/
private boolean isRemoved() {
return removed;
}
/**
* Sets the removed flag and clears the other state fields.
*/
private void setRemoved() {
removed = true;
needsPopulating = false;
needsCleaning = false;
clearPopulationParameters();
}
/*
* Clears the population parameters. Call when population is done, or
* reset to clear out the fields containing other, potentially large
* objects. This does not clear needsPopulating or lastPass.
*/
private void clearPopulationParameters() {
completed = null;
currentPartition = null;
lastKey = null;
lastData = null;
}
/*
* Resets the population of this secondary. The number of times
* this method is called is recorded. If the count is greater than
* or equal to the max lastError is set as the error string and the
* population will be stopped.
*
* @param exception the exception causing the reset
*/
void resetForPopulation(Exception exception) {
assert removed == false;
clearPopulationParameters();
needsPopulating = true;
/*
* Count the number of attempts. If over the limit set the error
* string which will stop population (needsPopulating will be
* set to false).
*/
populationAttempts++;
if (populationAttempts >= MAX_POPULATE_ATTEMPTS) {
setErrorString(exception);
}
/*
* Do not reset lastPass, totalReadKB and totalWriteKB as they are
* used for statistics and throttling.
*/
}
boolean isRebuild() {
return populationAttempts > 0;
}
@Override
public String toString() {
return "SecondaryInfo[" + needsPopulating +
", " + currentPartition +
", " + ((completed == null) ? "-" : completed.size()) +
", " + needsCleaning + ", " + removed +
", " + totalReadKB + ", " + totalWriteKB +
", " + populationAttempts +
", error: " + errorString +
"]";
}
}
/*
* Container for information on tables which are marked for deletion and
* need to have their repecitive data removed.
*/
static class DeletedTableInfo implements Serializable {
private static final long serialVersionUID = 1L;
/* True if the primary data has been cleaned */
private boolean done = false;
/* The partition being cleaned */
private PartitionId currentPartition = null;
private Set<PartitionId> completed = null;
private final boolean majorPathComplete;
/* Unused but maintained. */
private final boolean isChildTable;
private final long targetTableId;
private final byte[] parentKeyBytes;
/* holds the current state of the iteration for batching */
private byte[] currentKeyBytes;
/**
* Time of last of cleaning pass. This field was introduced after the
* initial release but does not need any upgrade consideration. It is
* used for an optimization, and can be lost in a mixed version shard.
*/
private long lastPass = 0;
DeletedTableInfo(TableImpl targetTable) {
TableImpl parentTable = targetTable;
/*
* If the target is a child table move the parentTable
* to the top-level parent. After this loop it is ok if
* parentTable == targetTable.
*/
if (targetTable.getParent() != null) {
isChildTable = true;
parentTable = targetTable.getTopLevelTable();
} else {
isChildTable = false;
}
final PrimaryKey pkey = parentTable.createPrimaryKey();
final TableKey key = TableKey.createKey(parentTable, pkey, true);
parentKeyBytes = key.getKeyBytes();
majorPathComplete = key.getMajorKeyComplete();
currentKeyBytes = parentKeyBytes;
targetTableId = targetTable.getId();
}
byte[] getCurrentKeyBytes() {
return currentKeyBytes;
}
void setCurrentKeyBytes(byte[] newKey) {
currentKeyBytes = newKey;
}
byte[] getParentKeyBytes() {
return parentKeyBytes;
}
long getTargetTableId() {
return targetTableId;
}
boolean getMajorPathComplete() {
return majorPathComplete;
}
boolean isChildTable() {
return isChildTable;
}
void completePass() {
lastPass = System.currentTimeMillis();
}
boolean isDone() {
return done;
}
boolean isCompleted(PartitionId partition) {
return (completed == null) ? false : completed.contains(partition);
}
/**
* Completes the current populate. Calling this method will add the
* current partition to the completed list and clear the current
* partition and last key.
*/
void completeCurrentPartition() {
if (completed == null) {
completed = new HashSet<>();
}
completed.add(currentPartition);
currentPartition = null;
}
PartitionId getCurrentPartition() {
return currentPartition;
}
void setCurrentPartition(PartitionId partition) {
currentPartition = partition;
}
void setDone() {
done = true;
}
@Override
public String toString() {
return "DeletedTableInfo[" + done + ", " + currentPartition +
", " + ((completed == null) ? "-" : completed.size()) + "]";
}
}
}
|
apache/dubbo | 38,232 | dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryDirectory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.integration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
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.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_CONVERT_URL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_DESTROY_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNSUPPORTED_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.APP_DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.COMPATIBLE_CONFIG_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.registry.Constants.ENABLE_26X_CONFIGURATION_LISTEN;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel;
/**
* RegistryDirectory
*/
public class RegistryDirectory<T> extends DynamicDirectory<T> {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RegistryDirectory.class);
private final ConsumerConfigurationListener consumerConfigurationListener;
private ReferenceConfigurationListener referenceConfigurationListener;
/**
* Map<url, Invoker> cache service url to invoker mapping.
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Map<URL, Invoker<T>> urlInvokerMap;
/**
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
protected volatile Set<URL> cachedInvokerUrls;
private final ModuleModel moduleModel;
public RegistryDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
moduleModel = getModuleModel(url.getScopeModel());
consumerConfigurationListener = getConsumerConfigurationListener(moduleModel);
}
@Override
public void subscribe(URL url) {
// Fail-fast detection protocol spi
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
if (StringUtils.isNotBlank(queryProtocols)) {
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (!moduleModel
.getApplicationModel()
.getExtensionLoader(Protocol.class)
.hasExtension(acceptProtocol)) {
throw new IllegalStateException("No such extension org.apache.dubbo.rpc.Protocol by name "
+ acceptProtocol + ", please check whether related SPI module is missing");
}
}
}
ApplicationModel applicationModel = url.getApplicationModel();
String registryClusterName = registry.getUrl()
.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
registry.getUrl().getParameter(PROTOCOL_KEY));
MetricsEventBus.post(RegistryEvent.toSubscribeEvent(applicationModel, registryClusterName), () -> {
super.subscribe(url);
return null;
});
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.addNotifyListener(this);
referenceConfigurationListener = new ReferenceConfigurationListener(moduleModel, this, url);
}
}
private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel));
}
@Override
public void unSubscribe(URL url) {
super.unSubscribe(url);
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public void destroy() {
super.destroy();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, org.apache.dubbo.registry.Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
consumerConfigurationListener.removeNotifyListener(this);
if (referenceConfigurationListener != null) {
referenceConfigurationListener.stop();
}
}
}
@Override
public synchronized void notify(List<URL> urls) {
if (isDestroyed()) {
return;
}
Map<String, List<URL>> categoryUrls = urls.stream()
.filter(Objects::nonNull)
.filter(this::isValidCategory)
.filter(this::isNotCompatibleFor26x)
.collect(Collectors.groupingBy(this::judgeCategory));
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, ENABLE_26X_CONFIGURATION_LISTEN, true)) {
List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
toRouters(routerURLs).ifPresent(this::addRouters);
}
// providers
List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
// 3.x added for extend URL address
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (supportedListeners != null && !supportedListeners.isEmpty()) {
for (AddressListener addressListener : supportedListeners) {
providerURLs = addressListener.notify(providerURLs, getConsumerUrl(), this);
}
}
refreshOverrideAndInvoker(providerURLs);
}
@Override
public boolean isServiceDiscovery() {
return false;
}
private String judgeCategory(URL url) {
if (UrlUtils.isConfigurator(url)) {
return CONFIGURATORS_CATEGORY;
} else if (UrlUtils.isRoute(url)) {
return ROUTERS_CATEGORY;
} else if (UrlUtils.isProvider(url)) {
return PROVIDERS_CATEGORY;
}
return "";
}
// RefreshOverrideAndInvoker will be executed by registryCenter and configCenter, so it should be synchronized.
@Override
protected synchronized void refreshOverrideAndInvoker(List<URL> urls) {
// mock zookeeper://xxx?mock=return null
this.directoryUrl = overrideWithConfigurator(getOriginalConsumerUrl());
refreshInvoker(urls);
}
/**
* Convert the invokerURL list to the Invoker Map. The rules of the conversion are as follows:
* <ol>
* <li> If URL has been converted to invoker, it is no longer re-referenced and obtained directly from the cache,
* and notice that any parameter changes in the URL will be re-referenced.</li>
* <li>If the incoming invoker list is not empty, it means that it is the latest invoker list.</li>
* <li>If the list of incoming invokerUrl is empty, It means that the rule is only a override rule or a route
* rule, which needs to be re-contrasted to decide whether to re-reference.</li>
* </ol>
*
* @param invokerUrls this parameter can't be null
*/
private void refreshInvoker(List<URL> invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null");
if (invokerUrls.size() == 1
&& invokerUrls.get(0) != null
&& EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
refreshRouter(
BitList.emptyList(), () -> this.forbidden = true // Forbid to access
);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow to access
if (invokerUrls == Collections.<URL>emptyList()) {
invokerUrls = new ArrayList<>();
}
// use local reference to avoid NPE as this.cachedInvokerUrls will be set null by destroyAllInvokers().
Set<URL> localCachedInvokerUrls = this.cachedInvokerUrls;
if (invokerUrls.isEmpty()) {
if (CollectionUtils.isNotEmpty(localCachedInvokerUrls)) {
// 1-4 Empty address.
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"configuration ",
"",
"Service" + serviceKey
+ " received empty address list with no EMPTY protocol set, trigger empty protection.");
invokerUrls.addAll(localCachedInvokerUrls);
}
} else {
localCachedInvokerUrls = new HashSet<>();
localCachedInvokerUrls.addAll(invokerUrls); // Cached invoker urls, convenient for comparison
this.cachedInvokerUrls = localCachedInvokerUrls;
}
if (invokerUrls.isEmpty()) {
return;
}
int originSize = invokerUrls.size();
invokerUrls = invokerUrls.stream().distinct().collect(Collectors.toList());
if (invokerUrls.size() != originSize) {
logger.info("Received duplicated invoker urls changed event from registry. "
+ "Registry type: interface. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". "
+ "Notify Urls Size : " + originSize + ". "
+ "Distinct Urls Size: " + invokerUrls.size() + ".");
}
// use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at
// destroyAllInvokers().
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;
// can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers().
Map<URL, Invoker<T>> oldUrlInvokerMap = null;
if (localUrlInvokerMap != null) {
// the initial capacity should be set greater than the maximum number of entries divided by the load
// factor to avoid resizing.
oldUrlInvokerMap =
new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR));
localUrlInvokerMap.forEach(oldUrlInvokerMap::put);
}
Map<URL, Invoker<T>> newUrlInvokerMap =
toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map
/*
* If the calculation is wrong, it is not processed.
*
* 1. The protocol configured by the client is inconsistent with the protocol of the server.
* eg: consumer protocol = dubbo, provider only has other protocol services(rest).
* 2. The registration center is not robust and pushes illegal specification data.
*
*/
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
// 3-1 - Failed to convert the URL address into Invokers.
logger.error(
PROXY_FAILED_CONVERT_URL,
"inconsistency between the client protocol and the protocol of the server",
"",
"urls to invokers error",
new IllegalStateException("urls to invokers error. invokerUrls.size :" + invokerUrls.size()
+ ", invoker.size :0. urls :" + invokerUrls.toString()));
return;
}
List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
BitList<Invoker<T>> finalInvokers =
multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers);
// pre-route and build cache
refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers));
this.urlInvokerMap = newUrlInvokerMap;
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn(REGISTRY_FAILED_DESTROY_SERVICE, "", "", "destroyUnusedInvokers error. ", e);
}
// notify invokers refreshed
this.invokersChanged();
}
logger.info("Received invokers changed event from registry. " + "Registry type: interface. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". " + "Urls Size : "
+ invokerUrls.size() + ". " + "Invokers Size : "
+ getInvokers().size() + ". " + "Available Size: "
+ getValidInvokers().size() + ". " + "Available Invokers : "
+ joinValidInvokerAddresses());
}
private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
List<Invoker<T>> mergedInvokers = new ArrayList<>();
Map<String, List<Invoker<T>>> groupMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String group = invoker.getUrl().getGroup("");
groupMap.computeIfAbsent(group, k -> new ArrayList<>());
groupMap.get(group).add(invoker);
}
if (groupMap.size() == 1) {
mergedInvokers.addAll(groupMap.values().iterator().next());
} else if (groupMap.size() > 1) {
for (List<Invoker<T>> groupList : groupMap.values()) {
StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
staticDirectory.buildRouterChain();
mergedInvokers.add(cluster.join(staticDirectory, false));
}
} else {
mergedInvokers = invokers;
}
return mergedInvokers;
}
/**
* @param urls
* @return null : no routers ,do nothing
* else :routers list
*/
private Optional<List<Router>> toRouters(List<URL> urls) {
if (urls == null || urls.isEmpty()) {
return Optional.empty();
}
List<Router> routers = new ArrayList<>();
for (URL url : urls) {
if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
continue;
}
String routerType = url.getParameter(ROUTER_KEY);
if (routerType != null && routerType.length() > 0) {
url = url.setProtocol(routerType);
}
try {
Router router = routerFactory.getRouter(url);
if (!routers.contains(router)) {
routers.add(router);
}
} catch (Throwable t) {
logger.error(PROXY_FAILED_CONVERT_URL, "", "", "convert router url to router error, url:" + url, t);
}
}
return Optional.of(routers);
}
/**
* Turn urls into invokers, and if url has been referred, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<URL, Invoker<T>> toInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<URL, Invoker<T>> newUrlInvokerMap =
new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1));
if (urls == null || urls.isEmpty()) {
return newUrlInvokerMap;
}
String queryProtocols = this.queryMap.get(PROTOCOL_KEY);
for (URL providerUrl : urls) {
if (!checkProtocolValid(queryProtocols, providerUrl)) {
continue;
}
URL url = mergeUrl(providerUrl);
// get the effective protocol that this consumer should consume based on consumer side protocol
// configuration and available protocols in address pool.
String effectiveProtocol = getEffectiveProtocol(queryProtocols, url);
if (!effectiveProtocol.equals(url.getProtocol())) {
url = url.setProtocol(effectiveProtocol);
}
// Cache key is url that does not merge with consumer side parameters,
// regardless of how the consumer combines parameters,
// if the server url changes, then refer again
Invoker<T> invoker = oldUrlInvokerMap == null ? null : oldUrlInvokerMap.remove(url);
if (invoker == null) { // Not in the cache, refer again
try {
boolean enabled = true;
if (url.hasParameter(DISABLED_KEY)) {
enabled = !url.getParameter(DISABLED_KEY, false);
} else {
enabled = url.getParameter(ENABLED_KEY, true);
}
if (enabled) {
invoker = protocol.refer(serviceType, url);
}
} catch (Throwable t) {
// Thrown by AbstractProtocol.optimizeSerialization()
if (t instanceof RpcException && t.getMessage().contains("serialization optimizer")) {
// 4-2 - serialization optimizer class initialization failed.
logger.error(
PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER,
"typo in optimizer class",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
} else {
// 4-3 - Failed to refer invoker by other reason.
logger.error(
PROTOCOL_FAILED_REFER_INVOKER,
"",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + url + ")"
+ t.getMessage(),
t);
}
}
if (invoker != null) { // Put new invoker in cache
newUrlInvokerMap.put(url, invoker);
}
} else {
newUrlInvokerMap.put(url, invoker);
}
}
return newUrlInvokerMap;
}
/**
* Get the protocol to consume by matching the consumer acceptable protocols and the available provider protocols.
* <p>
* Only the first protocol that can match with the provider protocols will be used if consumer set to accept multiple protocols.
* For example, if dubbo.consumer.protocol='tri,rest' is set and provider provides tri protocol, then consumer will use tri protocol to communicate with provider.
*
* @param queryProtocols consumer side protocols.
* @param url provider url that have extra protocols specified.
* @return the protocol to consume.
*/
private String getEffectiveProtocol(String queryProtocols, URL url) {
String protocol = url.getProtocol();
String prioritizedProtocol = url.getParameter(PREFERRED_PROTOCOL, protocol);
String effectiveProtocol = prioritizedProtocol;
if (StringUtils.isNotEmpty(queryProtocols)) {
String[] acceptProtocols = queryProtocols.split(COMMA_SEPARATOR);
String acceptedProtocol = acceptProtocols[0];
if (!acceptedProtocol.equals(prioritizedProtocol)) {
if (!acceptedProtocol.equals(protocol)) {
String extProtocols = url.getParameter(EXT_PROTOCOL);
if (StringUtils.isNotEmpty(extProtocols)) {
String[] extProtocolsArr = extProtocols.split(COMMA_SEPARATOR);
for (String p : extProtocolsArr) {
if (p.equalsIgnoreCase(acceptedProtocol)) {
effectiveProtocol = acceptedProtocol;
break;
}
}
}
} else {
effectiveProtocol = protocol;
}
}
}
return effectiveProtocol;
}
private boolean checkProtocolValid(String queryProtocols, URL providerUrl) {
// If protocol is configured at the reference side, only the matching protocol is selected
if (queryProtocols != null && queryProtocols.length() > 0) {
boolean accept = false;
String[] acceptProtocols = queryProtocols.split(",");
for (String acceptProtocol : acceptProtocols) {
if (providerUrl.getProtocol().equals(acceptProtocol)) {
accept = true;
break;
}
}
if (!accept) {
return false;
}
}
if (EMPTY_PROTOCOL.equals(providerUrl.getProtocol())) {
return false;
}
if (!getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.hasExtension(providerUrl.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(
PROTOCOL_UNSUPPORTED,
"protocol extension does not installed",
"",
"Unsupported protocol.",
new IllegalStateException("Unsupported protocol " + providerUrl.getProtocol() + " in notified url: "
+ providerUrl + " from registry " + getUrl().getAddress() + " to consumer "
+ NetUtils.getLocalHost() + ", supported protocol: "
+ getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.getSupportedExtensions()));
return false;
}
return true;
}
/**
* Merge url parameters. the order is: override > -D >Consumer > Provider
*
* @param providerUrl
* @return
*/
private URL mergeUrl(URL providerUrl) {
if (providerUrl instanceof ServiceAddressURL) {
providerUrl = overrideWithConfigurator(providerUrl);
} else {
providerUrl = moduleModel
.getApplicationModel()
.getBeanFactory()
.getBean(ClusterUtils.class)
.mergeUrl(providerUrl, queryMap); // Merge the consumer side parameters
providerUrl = overrideWithConfigurator(providerUrl);
providerUrl = providerUrl.addParameter(
Constants.CHECK_KEY,
String.valueOf(
false)); // Do not check whether the connection is successful or not, always create Invoker!
}
// FIXME, kept for mock
if (providerUrl.hasParameter(MOCK_KEY) || providerUrl.getAnyMethodParameter(MOCK_KEY) != null) {
providerUrl = providerUrl.removeParameter(MOCK_KEY);
}
if ((providerUrl.getPath() == null || providerUrl.getPath().length() == 0)
&& DUBBO_PROTOCOL.equals(providerUrl.getProtocol())) { // Compatible version 1.0
// fix by tony.chenl DUBBO-44
String path = directoryUrl.getServiceInterface();
if (path != null) {
int i = path.indexOf('/');
if (i >= 0) {
path = path.substring(i + 1);
}
i = path.lastIndexOf(':');
if (i >= 0) {
path = path.substring(0, i);
}
providerUrl = providerUrl.setPath(path);
}
}
return providerUrl;
}
protected URL overrideWithConfigurator(URL providerUrl) {
// override url with configurator from "override://" URL for dubbo 2.6 and before
providerUrl = overrideWithConfigurators(this.configurators, providerUrl);
// override url with configurator from "app-name.configurators"
providerUrl = overrideWithConfigurators(consumerConfigurationListener.getConfigurators(), providerUrl);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
providerUrl = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), providerUrl);
}
return providerUrl;
}
private URL overrideWithConfigurators(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
if (url instanceof DubboServiceAddressURL) {
DubboServiceAddressURL interfaceAddressURL = (DubboServiceAddressURL) url;
URL overriddenURL = interfaceAddressURL.getOverrideURL();
if (overriddenURL == null) {
String appName = interfaceAddressURL.getApplication();
String side = interfaceAddressURL.getSide();
String group = interfaceAddressURL.getGroup();
String version = interfaceAddressURL.getVersion();
overriddenURL = URLBuilder.from(interfaceAddressURL)
.clearParameters()
.addParameter(APPLICATION_KEY, appName)
.addParameter(SIDE_KEY, side)
.addParameter(GROUP_KEY, group)
.addParameter(VERSION_KEY, version)
.build();
}
for (Configurator configurator : configurators) {
overriddenURL = configurator.configure(overriddenURL);
}
url = new DubboServiceAddressURL(
interfaceAddressURL.getUrlAddress(),
interfaceAddressURL.getUrlParam(),
interfaceAddressURL.getConsumerURL(),
(ServiceConfigURL) overriddenURL);
} else {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
}
return url;
}
/**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
Map<URL, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference
if (!CollectionUtils.isEmptyMap(localUrlInvokerMap)) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
try {
invoker.destroy();
} catch (Throwable t) {
// 1-15 - Failed to destroy service
logger.warn(
REGISTRY_FAILED_DESTROY_SERVICE,
"",
"",
"Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(),
t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.cachedInvokerUrls = null;
destroyInvokers();
}
private void destroyUnusedInvokers(Map<URL, Invoker<T>> oldUrlInvokerMap, Map<URL, Invoker<T>> newUrlInvokerMap) {
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
destroyAllInvokers();
return;
}
if (CollectionUtils.isEmptyMap(oldUrlInvokerMap)) {
return;
}
for (Map.Entry<URL, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
Invoker<T> invoker = entry.getValue();
if (invoker != null) {
try {
invoker.destroy();
if (logger.isDebugEnabled()) {
logger.debug("destroy invoker[" + invoker.getUrl() + "] success. ");
}
} catch (Exception e) {
logger.warn(
REGISTRY_FAILED_DESTROY_SERVICE,
"",
"",
"destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(),
e);
}
}
}
logger.info(
"New url total size, " + newUrlInvokerMap.size() + ", destroyed total size " + oldUrlInvokerMap.size());
}
/**
* Haomin: added for test purpose
*/
public Map<URL, Invoker<T>> getUrlInvokerMap() {
return urlInvokerMap;
}
private boolean isValidCategory(URL url) {
String category = url.getCategory(DEFAULT_CATEGORY);
if ((ROUTERS_CATEGORY.equals(category) || ROUTE_PROTOCOL.equals(url.getProtocol()))
|| PROVIDERS_CATEGORY.equals(category)
|| CONFIGURATORS_CATEGORY.equals(category)
|| DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)
|| APP_DYNAMIC_CONFIGURATORS_CATEGORY.equals(category)) {
return true;
}
// 1-16 - Unsupported category in NotifyListener
logger.warn(
REGISTRY_UNSUPPORTED_CATEGORY,
"",
"",
"Unsupported category " + category + " in notified url: " + url + " from registry "
+ getUrl().getAddress() + " to consumer " + NetUtils.getLocalHost());
return false;
}
@Override
protected Map<String, String> getDirectoryMeta() {
String registryKey = Optional.ofNullable(getRegistry())
.map(Registry::getUrl)
.map(url -> url.getParameter(RegistryConstants.REGISTRY_CLUSTER_KEY, url.getProtocol()))
.orElse("unknown");
Map<String, String> metas = new HashMap<>();
metas.put(REGISTRY_KEY, registryKey);
metas.put(REGISTER_MODE_KEY, INTERFACE_REGISTER_MODE);
return metas;
}
private boolean isNotCompatibleFor26x(URL url) {
return StringUtils.isEmpty(url.getParameter(COMPATIBLE_CONFIG_KEY));
}
private static class ReferenceConfigurationListener extends AbstractConfiguratorListener {
private RegistryDirectory directory;
private URL url;
ReferenceConfigurationListener(ModuleModel moduleModel, RegistryDirectory directory, URL url) {
super(moduleModel);
this.directory = directory;
this.url = url;
this.initWith(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
void stop() {
this.stopListen(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
@Override
protected void notifyOverrides() {
// to notify configurator/router changes
directory.refreshOverrideAndInvoker(Collections.emptyList());
}
}
private static class ConsumerConfigurationListener extends AbstractConfiguratorListener {
List<RegistryDirectory> listeners = new ArrayList<>();
ConsumerConfigurationListener(ModuleModel moduleModel) {
super(moduleModel);
this.initWith(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX);
}
void addNotifyListener(RegistryDirectory listener) {
this.listeners.add(listener);
}
void removeNotifyListener(RegistryDirectory listener) {
this.listeners.remove(listener);
}
@Override
protected void notifyOverrides() {
listeners.forEach(listener -> listener.refreshOverrideAndInvoker(Collections.emptyList()));
}
}
@Override
public String toString() {
return "RegistryDirectory(" + "registry: " + getUrl().getAddress() + ")-" + super.toString();
}
}
|
googleapis/google-cloud-java | 38,062 | java-talent/proto-google-cloud-talent-v4beta1/src/main/java/com/google/cloud/talent/v4beta1/UpdateCompanyRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/talent/v4beta1/company_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.talent.v4beta1;
/**
*
*
* <pre>
* Request for updating a specified company.
* </pre>
*
* Protobuf type {@code google.cloud.talent.v4beta1.UpdateCompanyRequest}
*/
public final class UpdateCompanyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.talent.v4beta1.UpdateCompanyRequest)
UpdateCompanyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateCompanyRequest.newBuilder() to construct.
private UpdateCompanyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateCompanyRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateCompanyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.talent.v4beta1.CompanyServiceProto
.internal_static_google_cloud_talent_v4beta1_UpdateCompanyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.talent.v4beta1.CompanyServiceProto
.internal_static_google_cloud_talent_v4beta1_UpdateCompanyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.talent.v4beta1.UpdateCompanyRequest.class,
com.google.cloud.talent.v4beta1.UpdateCompanyRequest.Builder.class);
}
private int bitField0_;
public static final int COMPANY_FIELD_NUMBER = 1;
private com.google.cloud.talent.v4beta1.Company company_;
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the company field is set.
*/
@java.lang.Override
public boolean hasCompany() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The company.
*/
@java.lang.Override
public com.google.cloud.talent.v4beta1.Company getCompany() {
return company_ == null
? com.google.cloud.talent.v4beta1.Company.getDefaultInstance()
: company_;
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.talent.v4beta1.CompanyOrBuilder getCompanyOrBuilder() {
return company_ == null
? com.google.cloud.talent.v4beta1.Company.getDefaultInstance()
: company_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getCompany());
}
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, getCompany());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.talent.v4beta1.UpdateCompanyRequest)) {
return super.equals(obj);
}
com.google.cloud.talent.v4beta1.UpdateCompanyRequest other =
(com.google.cloud.talent.v4beta1.UpdateCompanyRequest) obj;
if (hasCompany() != other.hasCompany()) return false;
if (hasCompany()) {
if (!getCompany().equals(other.getCompany())) 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 (hasCompany()) {
hash = (37 * hash) + COMPANY_FIELD_NUMBER;
hash = (53 * hash) + getCompany().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.talent.v4beta1.UpdateCompanyRequest 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 updating a specified company.
* </pre>
*
* Protobuf type {@code google.cloud.talent.v4beta1.UpdateCompanyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.talent.v4beta1.UpdateCompanyRequest)
com.google.cloud.talent.v4beta1.UpdateCompanyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.talent.v4beta1.CompanyServiceProto
.internal_static_google_cloud_talent_v4beta1_UpdateCompanyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.talent.v4beta1.CompanyServiceProto
.internal_static_google_cloud_talent_v4beta1_UpdateCompanyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.talent.v4beta1.UpdateCompanyRequest.class,
com.google.cloud.talent.v4beta1.UpdateCompanyRequest.Builder.class);
}
// Construct using com.google.cloud.talent.v4beta1.UpdateCompanyRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getCompanyFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
company_ = null;
if (companyBuilder_ != null) {
companyBuilder_.dispose();
companyBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.talent.v4beta1.CompanyServiceProto
.internal_static_google_cloud_talent_v4beta1_UpdateCompanyRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.UpdateCompanyRequest getDefaultInstanceForType() {
return com.google.cloud.talent.v4beta1.UpdateCompanyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.UpdateCompanyRequest build() {
com.google.cloud.talent.v4beta1.UpdateCompanyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.UpdateCompanyRequest buildPartial() {
com.google.cloud.talent.v4beta1.UpdateCompanyRequest result =
new com.google.cloud.talent.v4beta1.UpdateCompanyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.talent.v4beta1.UpdateCompanyRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.company_ = companyBuilder_ == null ? company_ : companyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.talent.v4beta1.UpdateCompanyRequest) {
return mergeFrom((com.google.cloud.talent.v4beta1.UpdateCompanyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.talent.v4beta1.UpdateCompanyRequest other) {
if (other == com.google.cloud.talent.v4beta1.UpdateCompanyRequest.getDefaultInstance())
return this;
if (other.hasCompany()) {
mergeCompany(other.getCompany());
}
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(getCompanyFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.talent.v4beta1.Company company_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.talent.v4beta1.Company,
com.google.cloud.talent.v4beta1.Company.Builder,
com.google.cloud.talent.v4beta1.CompanyOrBuilder>
companyBuilder_;
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the company field is set.
*/
public boolean hasCompany() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The company.
*/
public com.google.cloud.talent.v4beta1.Company getCompany() {
if (companyBuilder_ == null) {
return company_ == null
? com.google.cloud.talent.v4beta1.Company.getDefaultInstance()
: company_;
} else {
return companyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setCompany(com.google.cloud.talent.v4beta1.Company value) {
if (companyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
company_ = value;
} else {
companyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setCompany(com.google.cloud.talent.v4beta1.Company.Builder builderForValue) {
if (companyBuilder_ == null) {
company_ = builderForValue.build();
} else {
companyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeCompany(com.google.cloud.talent.v4beta1.Company value) {
if (companyBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& company_ != null
&& company_ != com.google.cloud.talent.v4beta1.Company.getDefaultInstance()) {
getCompanyBuilder().mergeFrom(value);
} else {
company_ = value;
}
} else {
companyBuilder_.mergeFrom(value);
}
if (company_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearCompany() {
bitField0_ = (bitField0_ & ~0x00000001);
company_ = null;
if (companyBuilder_ != null) {
companyBuilder_.dispose();
companyBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.talent.v4beta1.Company.Builder getCompanyBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getCompanyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.talent.v4beta1.CompanyOrBuilder getCompanyOrBuilder() {
if (companyBuilder_ != null) {
return companyBuilder_.getMessageOrBuilder();
} else {
return company_ == null
? com.google.cloud.talent.v4beta1.Company.getDefaultInstance()
: company_;
}
}
/**
*
*
* <pre>
* Required. The company resource to replace the current resource in the
* system.
* </pre>
*
* <code>
* .google.cloud.talent.v4beta1.Company company = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.talent.v4beta1.Company,
com.google.cloud.talent.v4beta1.Company.Builder,
com.google.cloud.talent.v4beta1.CompanyOrBuilder>
getCompanyFieldBuilder() {
if (companyBuilder_ == null) {
companyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.talent.v4beta1.Company,
com.google.cloud.talent.v4beta1.Company.Builder,
com.google.cloud.talent.v4beta1.CompanyOrBuilder>(
getCompany(), getParentForChildren(), isClean());
company_ = null;
}
return companyBuilder_;
}
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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </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>
* Strongly recommended for the best service experience.
*
* If
* [update_mask][google.cloud.talent.v4beta1.UpdateCompanyRequest.update_mask]
* is provided, only the specified fields in
* [company][google.cloud.talent.v4beta1.UpdateCompanyRequest.company] are
* updated. Otherwise all the fields are updated.
*
* A field mask to specify the company fields to be updated. Only
* top level fields of [Company][google.cloud.talent.v4beta1.Company] are
* supported.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.talent.v4beta1.UpdateCompanyRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.talent.v4beta1.UpdateCompanyRequest)
private static final com.google.cloud.talent.v4beta1.UpdateCompanyRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.talent.v4beta1.UpdateCompanyRequest();
}
public static com.google.cloud.talent.v4beta1.UpdateCompanyRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateCompanyRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateCompanyRequest>() {
@java.lang.Override
public UpdateCompanyRequest 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<UpdateCompanyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateCompanyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.UpdateCompanyRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 38,088 | jdk/src/share/classes/sun/security/x509/AlgorithmId.java | /*
* Copyright (c) 1996, 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.security.x509;
import java.io.*;
import java.util.*;
import java.security.*;
import sun.security.util.*;
/**
* This class identifies algorithms, such as cryptographic transforms, each
* of which may be associated with parameters. Instances of this base class
* are used when this runtime environment has no special knowledge of the
* algorithm type, and may also be used in other cases. Equivalence is
* defined according to OID and (where relevant) parameters.
*
* <P>Subclasses may be used, for example when when the algorithm ID has
* associated parameters which some code (e.g. code using public keys) needs
* to have parsed. Two examples of such algorithms are Diffie-Hellman key
* exchange, and the Digital Signature Standard Algorithm (DSS/DSA).
*
* <P>The OID constants defined in this class correspond to some widely
* used algorithms, for which conventional string names have been defined.
* This class is not a general repository for OIDs, or for such string names.
* Note that the mappings between algorithm IDs and algorithm names is
* not one-to-one.
*
*
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
*/
public class AlgorithmId implements Serializable, DerEncoder {
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 7205873507486557157L;
/**
* The object identitifer being used for this algorithm.
*/
private ObjectIdentifier algid;
// The (parsed) parameters
private AlgorithmParameters algParams;
private boolean constructedFromDer = true;
/**
* Parameters for this algorithm. These are stored in unparsed
* DER-encoded form; subclasses can be made to automaticaly parse
* them so there is fast access to these parameters.
*/
protected DerValue params;
/**
* Constructs an algorithm ID which will be initialized
* separately, for example by deserialization.
* @deprecated use one of the other constructors.
*/
@Deprecated
public AlgorithmId() { }
/**
* Constructs a parameterless algorithm ID.
*
* @param oid the identifier for the algorithm
*/
public AlgorithmId(ObjectIdentifier oid) {
algid = oid;
}
/**
* Constructs an algorithm ID with algorithm parameters.
*
* @param oid the identifier for the algorithm.
* @param algparams the associated algorithm parameters.
*/
public AlgorithmId(ObjectIdentifier oid, AlgorithmParameters algparams) {
algid = oid;
algParams = algparams;
constructedFromDer = false;
}
private AlgorithmId(ObjectIdentifier oid, DerValue params)
throws IOException {
this.algid = oid;
this.params = params;
if (this.params != null) {
decodeParams();
}
}
protected void decodeParams() throws IOException {
String algidString = algid.toString();
try {
algParams = AlgorithmParameters.getInstance(algidString);
} catch (NoSuchAlgorithmException e) {
/*
* This algorithm parameter type is not supported, so we cannot
* parse the parameters.
*/
algParams = null;
return;
}
// Decode (parse) the parameters
algParams.init(params.toByteArray());
}
/**
* Marshal a DER-encoded "AlgorithmID" sequence on the DER stream.
*/
public final void encode(DerOutputStream out) throws IOException {
derEncode(out);
}
/**
* DER encode this object onto an output stream.
* Implements the <code>DerEncoder</code> interface.
*
* @param out
* the output stream on which to write the DER encoding.
*
* @exception IOException on encoding error.
*/
public void derEncode (OutputStream out) throws IOException {
DerOutputStream bytes = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
bytes.putOID(algid);
// Setup params from algParams since no DER encoding is given
if (constructedFromDer == false) {
if (algParams != null) {
params = new DerValue(algParams.getEncoded());
} else {
params = null;
}
}
if (params == null) {
// Changes backed out for compatibility with Solaris
// Several AlgorithmId should omit the whole parameter part when
// it's NULL. They are ---
// rfc3370 2.1: Implementations SHOULD generate SHA-1
// AlgorithmIdentifiers with absent parameters.
// rfc3447 C1: When id-sha1, id-sha224, id-sha256, id-sha384 and
// id-sha512 are used in an AlgorithmIdentifier the parameters
// (which are optional) SHOULD be omitted.
// rfc3279 2.3.2: The id-dsa algorithm syntax includes optional
// domain parameters... When omitted, the parameters component
// MUST be omitted entirely
// rfc3370 3.1: When the id-dsa-with-sha1 algorithm identifier
// is used, the AlgorithmIdentifier parameters field MUST be absent.
/*if (
algid.equals((Object)SHA_oid) ||
algid.equals((Object)SHA224_oid) ||
algid.equals((Object)SHA256_oid) ||
algid.equals((Object)SHA384_oid) ||
algid.equals((Object)SHA512_oid) ||
algid.equals((Object)DSA_oid) ||
algid.equals((Object)sha1WithDSA_oid)) {
; // no parameter part encoded
} else {
bytes.putNull();
}*/
bytes.putNull();
} else {
bytes.putDerValue(params);
}
tmp.write(DerValue.tag_Sequence, bytes);
out.write(tmp.toByteArray());
}
/**
* Returns the DER-encoded X.509 AlgorithmId as a byte array.
*/
public final byte[] encode() throws IOException {
DerOutputStream out = new DerOutputStream();
derEncode(out);
return out.toByteArray();
}
/**
* Returns the ISO OID for this algorithm. This is usually converted
* to a string and used as part of an algorithm name, for example
* "OID.1.3.14.3.2.13" style notation. Use the <code>getName</code>
* call when you do not need to ensure cross-system portability
* of algorithm names, or need a user friendly name.
*/
public final ObjectIdentifier getOID () {
return algid;
}
/**
* Returns a name for the algorithm which may be more intelligible
* to humans than the algorithm's OID, but which won't necessarily
* be comprehensible on other systems. For example, this might
* return a name such as "MD5withRSA" for a signature algorithm on
* some systems. It also returns names like "OID.1.2.3.4", when
* no particular name for the algorithm is known.
*/
public String getName() {
String algName = nameTable.get(algid);
if (algName != null) {
return algName;
}
if ((params != null) && algid.equals((Object)specifiedWithECDSA_oid)) {
try {
AlgorithmId paramsId =
AlgorithmId.parse(new DerValue(getEncodedParams()));
String paramsName = paramsId.getName();
algName = makeSigAlg(paramsName, "EC");
} catch (IOException e) {
// ignore
}
}
return (algName == null) ? algid.toString() : algName;
}
public AlgorithmParameters getParameters() {
return algParams;
}
/**
* Returns the DER encoded parameter, which can then be
* used to initialize java.security.AlgorithmParamters.
*
* @return DER encoded parameters, or null not present.
*/
public byte[] getEncodedParams() throws IOException {
return (params == null) ? null : params.toByteArray();
}
/**
* Returns true iff the argument indicates the same algorithm
* with the same parameters.
*/
public boolean equals(AlgorithmId other) {
boolean paramsEqual =
(params == null ? other.params == null : params.equals(other.params));
return (algid.equals((Object)other.algid) && paramsEqual);
}
/**
* Compares this AlgorithmID to another. If algorithm parameters are
* available, they are compared. Otherwise, just the object IDs
* for the algorithm are compared.
*
* @param other preferably an AlgorithmId, else an ObjectIdentifier
*/
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof AlgorithmId) {
return equals((AlgorithmId) other);
} else if (other instanceof ObjectIdentifier) {
return equals((ObjectIdentifier) other);
} else {
return false;
}
}
/**
* Compares two algorithm IDs for equality. Returns true iff
* they are the same algorithm, ignoring algorithm parameters.
*/
public final boolean equals(ObjectIdentifier id) {
return algid.equals((Object)id);
}
/**
* Returns a hashcode for this AlgorithmId.
*
* @return a hashcode for this AlgorithmId.
*/
public int hashCode() {
StringBuilder sbuf = new StringBuilder();
sbuf.append(algid.toString());
sbuf.append(paramsToString());
return sbuf.toString().hashCode();
}
/**
* Provides a human-readable description of the algorithm parameters.
* This may be redefined by subclasses which parse those parameters.
*/
protected String paramsToString() {
if (params == null) {
return "";
} else if (algParams != null) {
return algParams.toString();
} else {
return ", params unparsed";
}
}
/**
* Returns a string describing the algorithm and its parameters.
*/
public String toString() {
return getName() + paramsToString();
}
/**
* Parse (unmarshal) an ID from a DER sequence input value. This form
* parsing might be used when expanding a value which has already been
* partially unmarshaled as a set or sequence member.
*
* @exception IOException on error.
* @param val the input value, which contains the algid and, if
* there are any parameters, those parameters.
* @return an ID for the algorithm. If the system is configured
* appropriately, this may be an instance of a class
* with some kind of special support for this algorithm.
* In that case, you may "narrow" the type of the ID.
*/
public static AlgorithmId parse(DerValue val) throws IOException {
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("algid parse error, not a sequence");
}
/*
* Get the algorithm ID and any parameters.
*/
ObjectIdentifier algid;
DerValue params;
DerInputStream in = val.toDerInputStream();
algid = in.getOID();
if (in.available() == 0) {
params = null;
} else {
params = in.getDerValue();
if (params.tag == DerValue.tag_Null) {
if (params.length() != 0) {
throw new IOException("invalid NULL");
}
params = null;
}
if (in.available() != 0) {
throw new IOException("Invalid AlgorithmIdentifier: extra data");
}
}
return new AlgorithmId(algid, params);
}
/**
* Returns one of the algorithm IDs most commonly associated
* with this algorithm name.
*
* @param algname the name being used
* @deprecated use the short get form of this method.
* @exception NoSuchAlgorithmException on error.
*/
@Deprecated
public static AlgorithmId getAlgorithmId(String algname)
throws NoSuchAlgorithmException {
return get(algname);
}
/**
* Returns one of the algorithm IDs most commonly associated
* with this algorithm name.
*
* @param algname the name being used
* @exception NoSuchAlgorithmException on error.
*/
public static AlgorithmId get(String algname)
throws NoSuchAlgorithmException {
ObjectIdentifier oid;
try {
oid = algOID(algname);
} catch (IOException ioe) {
throw new NoSuchAlgorithmException
("Invalid ObjectIdentifier " + algname);
}
if (oid == null) {
throw new NoSuchAlgorithmException
("unrecognized algorithm name: " + algname);
}
return new AlgorithmId(oid);
}
/**
* Returns one of the algorithm IDs most commonly associated
* with this algorithm parameters.
*
* @param algparams the associated algorithm parameters.
* @exception NoSuchAlgorithmException on error.
*/
public static AlgorithmId get(AlgorithmParameters algparams)
throws NoSuchAlgorithmException {
ObjectIdentifier oid;
String algname = algparams.getAlgorithm();
try {
oid = algOID(algname);
} catch (IOException ioe) {
throw new NoSuchAlgorithmException
("Invalid ObjectIdentifier " + algname);
}
if (oid == null) {
throw new NoSuchAlgorithmException
("unrecognized algorithm name: " + algname);
}
return new AlgorithmId(oid, algparams);
}
/*
* Translates from some common algorithm names to the
* OID with which they're usually associated ... this mapping
* is the reverse of the one below, except in those cases
* where synonyms are supported or where a given algorithm
* is commonly associated with multiple OIDs.
*
* XXX This method needs to be enhanced so that we can also pass the
* scope of the algorithm name to it, e.g., the algorithm name "DSA"
* may have a different OID when used as a "Signature" algorithm than when
* used as a "KeyPairGenerator" algorithm.
*/
private static ObjectIdentifier algOID(String name) throws IOException {
// See if algname is in printable OID ("dot-dot") notation
if (name.indexOf('.') != -1) {
if (name.startsWith("OID.")) {
return new ObjectIdentifier(name.substring("OID.".length()));
} else {
return new ObjectIdentifier(name);
}
}
// Digesting algorithms
if (name.equalsIgnoreCase("MD5")) {
return AlgorithmId.MD5_oid;
}
if (name.equalsIgnoreCase("MD2")) {
return AlgorithmId.MD2_oid;
}
if (name.equalsIgnoreCase("SHA") || name.equalsIgnoreCase("SHA1")
|| name.equalsIgnoreCase("SHA-1")) {
return AlgorithmId.SHA_oid;
}
if (name.equalsIgnoreCase("SHA-256") ||
name.equalsIgnoreCase("SHA256")) {
return AlgorithmId.SHA256_oid;
}
if (name.equalsIgnoreCase("SHA-384") ||
name.equalsIgnoreCase("SHA384")) {
return AlgorithmId.SHA384_oid;
}
if (name.equalsIgnoreCase("SHA-512") ||
name.equalsIgnoreCase("SHA512")) {
return AlgorithmId.SHA512_oid;
}
if (name.equalsIgnoreCase("SHA-224") ||
name.equalsIgnoreCase("SHA224")) {
return AlgorithmId.SHA224_oid;
}
// Various public key algorithms
if (name.equalsIgnoreCase("RSA")) {
return AlgorithmId.RSAEncryption_oid;
}
if (name.equalsIgnoreCase("Diffie-Hellman")
|| name.equalsIgnoreCase("DH")) {
return AlgorithmId.DH_oid;
}
if (name.equalsIgnoreCase("DSA")) {
return AlgorithmId.DSA_oid;
}
if (name.equalsIgnoreCase("EC")) {
return EC_oid;
}
if (name.equalsIgnoreCase("ECDH")) {
return AlgorithmId.ECDH_oid;
}
// Secret key algorithms
if (name.equalsIgnoreCase("AES")) {
return AlgorithmId.AES_oid;
}
// Common signature types
if (name.equalsIgnoreCase("MD5withRSA")
|| name.equalsIgnoreCase("MD5/RSA")) {
return AlgorithmId.md5WithRSAEncryption_oid;
}
if (name.equalsIgnoreCase("MD2withRSA")
|| name.equalsIgnoreCase("MD2/RSA")) {
return AlgorithmId.md2WithRSAEncryption_oid;
}
if (name.equalsIgnoreCase("SHAwithDSA")
|| name.equalsIgnoreCase("SHA1withDSA")
|| name.equalsIgnoreCase("SHA/DSA")
|| name.equalsIgnoreCase("SHA1/DSA")
|| name.equalsIgnoreCase("DSAWithSHA1")
|| name.equalsIgnoreCase("DSS")
|| name.equalsIgnoreCase("SHA-1/DSA")) {
return AlgorithmId.sha1WithDSA_oid;
}
if (name.equalsIgnoreCase("SHA224WithDSA")) {
return AlgorithmId.sha224WithDSA_oid;
}
if (name.equalsIgnoreCase("SHA256WithDSA")) {
return AlgorithmId.sha256WithDSA_oid;
}
if (name.equalsIgnoreCase("SHA1WithRSA")
|| name.equalsIgnoreCase("SHA1/RSA")) {
return AlgorithmId.sha1WithRSAEncryption_oid;
}
if (name.equalsIgnoreCase("SHA1withECDSA")
|| name.equalsIgnoreCase("ECDSA")) {
return AlgorithmId.sha1WithECDSA_oid;
}
if (name.equalsIgnoreCase("SHA224withECDSA")) {
return AlgorithmId.sha224WithECDSA_oid;
}
if (name.equalsIgnoreCase("SHA256withECDSA")) {
return AlgorithmId.sha256WithECDSA_oid;
}
if (name.equalsIgnoreCase("SHA384withECDSA")) {
return AlgorithmId.sha384WithECDSA_oid;
}
if (name.equalsIgnoreCase("SHA512withECDSA")) {
return AlgorithmId.sha512WithECDSA_oid;
}
// See if any of the installed providers supply a mapping from
// the given algorithm name to an OID string
String oidString;
if (!initOidTable) {
Provider[] provs = Security.getProviders();
for (int i=0; i<provs.length; i++) {
for (Enumeration<Object> enum_ = provs[i].keys();
enum_.hasMoreElements(); ) {
String alias = (String)enum_.nextElement();
String upperCaseAlias = alias.toUpperCase(Locale.ENGLISH);
int index;
if (upperCaseAlias.startsWith("ALG.ALIAS") &&
(index=upperCaseAlias.indexOf("OID.", 0)) != -1) {
index += "OID.".length();
if (index == alias.length()) {
// invalid alias entry
break;
}
if (oidTable == null) {
oidTable = new HashMap<String,ObjectIdentifier>();
}
oidString = alias.substring(index);
String stdAlgName = provs[i].getProperty(alias);
if (stdAlgName != null) {
stdAlgName = stdAlgName.toUpperCase(Locale.ENGLISH);
}
if (stdAlgName != null &&
oidTable.get(stdAlgName) == null) {
oidTable.put(stdAlgName,
new ObjectIdentifier(oidString));
}
}
}
}
if (oidTable == null) {
oidTable = new HashMap<String,ObjectIdentifier>(1);
}
initOidTable = true;
}
return oidTable.get(name.toUpperCase(Locale.ENGLISH));
}
private static ObjectIdentifier oid(int ... values) {
return ObjectIdentifier.newInternal(values);
}
private static boolean initOidTable = false;
private static Map<String,ObjectIdentifier> oidTable;
private static final Map<ObjectIdentifier,String> nameTable;
/*****************************************************************/
/*
* HASHING ALGORITHMS
*/
/**
* Algorithm ID for the MD2 Message Digest Algorthm, from RFC 1319.
* OID = 1.2.840.113549.2.2
*/
public static final ObjectIdentifier MD2_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 2, 2});
/**
* Algorithm ID for the MD5 Message Digest Algorthm, from RFC 1321.
* OID = 1.2.840.113549.2.5
*/
public static final ObjectIdentifier MD5_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 2, 5});
/**
* Algorithm ID for the SHA1 Message Digest Algorithm, from FIPS 180-1.
* This is sometimes called "SHA", though that is often confusing since
* many people refer to FIPS 180 (which has an error) as defining SHA.
* OID = 1.3.14.3.2.26. Old SHA-0 OID: 1.3.14.3.2.18.
*/
public static final ObjectIdentifier SHA_oid =
ObjectIdentifier.newInternal(new int[] {1, 3, 14, 3, 2, 26});
public static final ObjectIdentifier SHA224_oid =
ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 4});
public static final ObjectIdentifier SHA256_oid =
ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 1});
public static final ObjectIdentifier SHA384_oid =
ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 2});
public static final ObjectIdentifier SHA512_oid =
ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 3});
/*
* COMMON PUBLIC KEY TYPES
*/
private static final int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 };
private static final int DH_PKIX_data[] = { 1, 2, 840, 10046, 2, 1 };
private static final int DSA_OIW_data[] = { 1, 3, 14, 3, 2, 12 };
private static final int DSA_PKIX_data[] = { 1, 2, 840, 10040, 4, 1 };
private static final int RSA_data[] = { 2, 5, 8, 1, 1 };
private static final int RSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 1 };
public static final ObjectIdentifier DH_oid;
public static final ObjectIdentifier DH_PKIX_oid;
public static final ObjectIdentifier DSA_oid;
public static final ObjectIdentifier DSA_OIW_oid;
public static final ObjectIdentifier EC_oid = oid(1, 2, 840, 10045, 2, 1);
public static final ObjectIdentifier ECDH_oid = oid(1, 3, 132, 1, 12);
public static final ObjectIdentifier RSA_oid;
public static final ObjectIdentifier RSAEncryption_oid;
/*
* COMMON SECRET KEY TYPES
*/
public static final ObjectIdentifier AES_oid =
oid(2, 16, 840, 1, 101, 3, 4, 1);
/*
* COMMON SIGNATURE ALGORITHMS
*/
private static final int md2WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 2 };
private static final int md5WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 4 };
private static final int sha1WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 5 };
private static final int sha1WithRSAEncryption_OIW_data[] =
{ 1, 3, 14, 3, 2, 29 };
private static final int sha224WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 14 };
private static final int sha256WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 11 };
private static final int sha384WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 12 };
private static final int sha512WithRSAEncryption_data[] =
{ 1, 2, 840, 113549, 1, 1, 13 };
private static final int shaWithDSA_OIW_data[] =
{ 1, 3, 14, 3, 2, 13 };
private static final int sha1WithDSA_OIW_data[] =
{ 1, 3, 14, 3, 2, 27 };
private static final int dsaWithSHA1_PKIX_data[] =
{ 1, 2, 840, 10040, 4, 3 };
public static final ObjectIdentifier md2WithRSAEncryption_oid;
public static final ObjectIdentifier md5WithRSAEncryption_oid;
public static final ObjectIdentifier sha1WithRSAEncryption_oid;
public static final ObjectIdentifier sha1WithRSAEncryption_OIW_oid;
public static final ObjectIdentifier sha224WithRSAEncryption_oid;
public static final ObjectIdentifier sha256WithRSAEncryption_oid;
public static final ObjectIdentifier sha384WithRSAEncryption_oid;
public static final ObjectIdentifier sha512WithRSAEncryption_oid;
public static final ObjectIdentifier shaWithDSA_OIW_oid;
public static final ObjectIdentifier sha1WithDSA_OIW_oid;
public static final ObjectIdentifier sha1WithDSA_oid;
public static final ObjectIdentifier sha224WithDSA_oid =
oid(2, 16, 840, 1, 101, 3, 4, 3, 1);
public static final ObjectIdentifier sha256WithDSA_oid =
oid(2, 16, 840, 1, 101, 3, 4, 3, 2);
public static final ObjectIdentifier sha1WithECDSA_oid =
oid(1, 2, 840, 10045, 4, 1);
public static final ObjectIdentifier sha224WithECDSA_oid =
oid(1, 2, 840, 10045, 4, 3, 1);
public static final ObjectIdentifier sha256WithECDSA_oid =
oid(1, 2, 840, 10045, 4, 3, 2);
public static final ObjectIdentifier sha384WithECDSA_oid =
oid(1, 2, 840, 10045, 4, 3, 3);
public static final ObjectIdentifier sha512WithECDSA_oid =
oid(1, 2, 840, 10045, 4, 3, 4);
public static final ObjectIdentifier specifiedWithECDSA_oid =
oid(1, 2, 840, 10045, 4, 3);
/**
* Algorithm ID for the PBE encryption algorithms from PKCS#5 and
* PKCS#12.
*/
public static final ObjectIdentifier pbeWithMD5AndDES_oid =
ObjectIdentifier.newInternal(new int[]{1, 2, 840, 113549, 1, 5, 3});
public static final ObjectIdentifier pbeWithMD5AndRC2_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 6});
public static final ObjectIdentifier pbeWithSHA1AndDES_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 10});
public static final ObjectIdentifier pbeWithSHA1AndRC2_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 11});
public static ObjectIdentifier pbeWithSHA1AndDESede_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 3});
public static ObjectIdentifier pbeWithSHA1AndRC2_40_oid =
ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 6});
static {
/*
* Note the preferred OIDs are named simply with no "OIW" or
* "PKIX" in them, even though they may point to data from these
* specs; e.g. SHA_oid, DH_oid, DSA_oid, SHA1WithDSA_oid...
*/
/**
* Algorithm ID for Diffie Hellman Key agreement, from PKCS #3.
* Parameters include public values P and G, and may optionally specify
* the length of the private key X. Alternatively, algorithm parameters
* may be derived from another source such as a Certificate Authority's
* certificate.
* OID = 1.2.840.113549.1.3.1
*/
DH_oid = ObjectIdentifier.newInternal(DH_data);
/**
* Algorithm ID for the Diffie Hellman Key Agreement (DH), from RFC 3279.
* Parameters may include public values P and G.
* OID = 1.2.840.10046.2.1
*/
DH_PKIX_oid = ObjectIdentifier.newInternal(DH_PKIX_data);
/**
* Algorithm ID for the Digital Signing Algorithm (DSA), from the
* NIST OIW Stable Agreements part 12.
* Parameters may include public values P, Q, and G; or these may be
* derived from
* another source such as a Certificate Authority's certificate.
* OID = 1.3.14.3.2.12
*/
DSA_OIW_oid = ObjectIdentifier.newInternal(DSA_OIW_data);
/**
* Algorithm ID for the Digital Signing Algorithm (DSA), from RFC 3279.
* Parameters may include public values P, Q, and G; or these may be
* derived from another source such as a Certificate Authority's
* certificate.
* OID = 1.2.840.10040.4.1
*/
DSA_oid = ObjectIdentifier.newInternal(DSA_PKIX_data);
/**
* Algorithm ID for RSA keys used for any purpose, as defined in X.509.
* The algorithm parameter is a single value, the number of bits in the
* public modulus.
* OID = 2.5.8.1.1
*/
RSA_oid = ObjectIdentifier.newInternal(RSA_data);
/**
* Algorithm ID for RSA keys used with RSA encryption, as defined
* in PKCS #1. There are no parameters associated with this algorithm.
* OID = 1.2.840.113549.1.1.1
*/
RSAEncryption_oid = ObjectIdentifier.newInternal(RSAEncryption_data);
/**
* Identifies a signing algorithm where an MD2 digest is encrypted
* using an RSA private key; defined in PKCS #1. Use of this
* signing algorithm is discouraged due to MD2 vulnerabilities.
* OID = 1.2.840.113549.1.1.2
*/
md2WithRSAEncryption_oid =
ObjectIdentifier.newInternal(md2WithRSAEncryption_data);
/**
* Identifies a signing algorithm where an MD5 digest is
* encrypted using an RSA private key; defined in PKCS #1.
* OID = 1.2.840.113549.1.1.4
*/
md5WithRSAEncryption_oid =
ObjectIdentifier.newInternal(md5WithRSAEncryption_data);
/**
* Identifies a signing algorithm where a SHA1 digest is
* encrypted using an RSA private key; defined by RSA DSI.
* OID = 1.2.840.113549.1.1.5
*/
sha1WithRSAEncryption_oid =
ObjectIdentifier.newInternal(sha1WithRSAEncryption_data);
/**
* Identifies a signing algorithm where a SHA1 digest is
* encrypted using an RSA private key; defined in NIST OIW.
* OID = 1.3.14.3.2.29
*/
sha1WithRSAEncryption_OIW_oid =
ObjectIdentifier.newInternal(sha1WithRSAEncryption_OIW_data);
/**
* Identifies a signing algorithm where a SHA224 digest is
* encrypted using an RSA private key; defined by PKCS #1.
* OID = 1.2.840.113549.1.1.14
*/
sha224WithRSAEncryption_oid =
ObjectIdentifier.newInternal(sha224WithRSAEncryption_data);
/**
* Identifies a signing algorithm where a SHA256 digest is
* encrypted using an RSA private key; defined by PKCS #1.
* OID = 1.2.840.113549.1.1.11
*/
sha256WithRSAEncryption_oid =
ObjectIdentifier.newInternal(sha256WithRSAEncryption_data);
/**
* Identifies a signing algorithm where a SHA384 digest is
* encrypted using an RSA private key; defined by PKCS #1.
* OID = 1.2.840.113549.1.1.12
*/
sha384WithRSAEncryption_oid =
ObjectIdentifier.newInternal(sha384WithRSAEncryption_data);
/**
* Identifies a signing algorithm where a SHA512 digest is
* encrypted using an RSA private key; defined by PKCS #1.
* OID = 1.2.840.113549.1.1.13
*/
sha512WithRSAEncryption_oid =
ObjectIdentifier.newInternal(sha512WithRSAEncryption_data);
/**
* Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
* SHA digest is signed using the Digital Signing Algorithm (DSA).
* This should not be used.
* OID = 1.3.14.3.2.13
*/
shaWithDSA_OIW_oid = ObjectIdentifier.newInternal(shaWithDSA_OIW_data);
/**
* Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
* SHA1 digest is signed using the Digital Signing Algorithm (DSA).
* OID = 1.3.14.3.2.27
*/
sha1WithDSA_OIW_oid = ObjectIdentifier.newInternal(sha1WithDSA_OIW_data);
/**
* Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
* SHA1 digest is signed using the Digital Signing Algorithm (DSA).
* OID = 1.2.840.10040.4.3
*/
sha1WithDSA_oid = ObjectIdentifier.newInternal(dsaWithSHA1_PKIX_data);
nameTable = new HashMap<ObjectIdentifier,String>();
nameTable.put(MD5_oid, "MD5");
nameTable.put(MD2_oid, "MD2");
nameTable.put(SHA_oid, "SHA-1");
nameTable.put(SHA224_oid, "SHA-224");
nameTable.put(SHA256_oid, "SHA-256");
nameTable.put(SHA384_oid, "SHA-384");
nameTable.put(SHA512_oid, "SHA-512");
nameTable.put(RSAEncryption_oid, "RSA");
nameTable.put(RSA_oid, "RSA");
nameTable.put(DH_oid, "Diffie-Hellman");
nameTable.put(DH_PKIX_oid, "Diffie-Hellman");
nameTable.put(DSA_oid, "DSA");
nameTable.put(DSA_OIW_oid, "DSA");
nameTable.put(EC_oid, "EC");
nameTable.put(ECDH_oid, "ECDH");
nameTable.put(AES_oid, "AES");
nameTable.put(sha1WithECDSA_oid, "SHA1withECDSA");
nameTable.put(sha224WithECDSA_oid, "SHA224withECDSA");
nameTable.put(sha256WithECDSA_oid, "SHA256withECDSA");
nameTable.put(sha384WithECDSA_oid, "SHA384withECDSA");
nameTable.put(sha512WithECDSA_oid, "SHA512withECDSA");
nameTable.put(md5WithRSAEncryption_oid, "MD5withRSA");
nameTable.put(md2WithRSAEncryption_oid, "MD2withRSA");
nameTable.put(sha1WithDSA_oid, "SHA1withDSA");
nameTable.put(sha1WithDSA_OIW_oid, "SHA1withDSA");
nameTable.put(shaWithDSA_OIW_oid, "SHA1withDSA");
nameTable.put(sha224WithDSA_oid, "SHA224withDSA");
nameTable.put(sha256WithDSA_oid, "SHA256withDSA");
nameTable.put(sha1WithRSAEncryption_oid, "SHA1withRSA");
nameTable.put(sha1WithRSAEncryption_OIW_oid, "SHA1withRSA");
nameTable.put(sha224WithRSAEncryption_oid, "SHA224withRSA");
nameTable.put(sha256WithRSAEncryption_oid, "SHA256withRSA");
nameTable.put(sha384WithRSAEncryption_oid, "SHA384withRSA");
nameTable.put(sha512WithRSAEncryption_oid, "SHA512withRSA");
nameTable.put(pbeWithMD5AndDES_oid, "PBEWithMD5AndDES");
nameTable.put(pbeWithMD5AndRC2_oid, "PBEWithMD5AndRC2");
nameTable.put(pbeWithSHA1AndDES_oid, "PBEWithSHA1AndDES");
nameTable.put(pbeWithSHA1AndRC2_oid, "PBEWithSHA1AndRC2");
nameTable.put(pbeWithSHA1AndDESede_oid, "PBEWithSHA1AndDESede");
nameTable.put(pbeWithSHA1AndRC2_40_oid, "PBEWithSHA1AndRC2_40");
}
/**
* Creates a signature algorithm name from a digest algorithm
* name and a encryption algorithm name.
*/
public static String makeSigAlg(String digAlg, String encAlg) {
digAlg = digAlg.replace("-", "");
if (encAlg.equalsIgnoreCase("EC")) encAlg = "ECDSA";
return digAlg + "with" + encAlg;
}
/**
* Extracts the encryption algorithm name from a signature
* algorithm name.
*/
public static String getEncAlgFromSigAlg(String signatureAlgorithm) {
signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
int with = signatureAlgorithm.indexOf("WITH");
String keyAlgorithm = null;
if (with > 0) {
int and = signatureAlgorithm.indexOf("AND", with + 4);
if (and > 0) {
keyAlgorithm = signatureAlgorithm.substring(with + 4, and);
} else {
keyAlgorithm = signatureAlgorithm.substring(with + 4);
}
if (keyAlgorithm.equalsIgnoreCase("ECDSA")) {
keyAlgorithm = "EC";
}
}
return keyAlgorithm;
}
/**
* Extracts the digest algorithm name from a signature
* algorithm name.
*/
public static String getDigAlgFromSigAlg(String signatureAlgorithm) {
signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
int with = signatureAlgorithm.indexOf("WITH");
if (with > 0) {
return signatureAlgorithm.substring(0, with);
}
return null;
}
}
|
apache/roller | 37,979 | app/src/main/java/org/apache/roller/weblogger/util/Utilities.java | package org.apache.roller.weblogger.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.roller.util.RegexUtil;
import org.apache.roller.util.RollerConstants;
/**
* General purpose utilities, not for use in templates.
*/
public class Utilities {
/** The <code>Log</code> instance for this class. */
private static final Log mLogger = LogFactory.getLog(Utilities.class);
public static final String TAG_SPLIT_CHARS = " ,\n\r\f\t";
private static final Pattern mLinkPattern = Pattern.compile("<a href=.*?>",
Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_B_TAG_PATTERN = Pattern.compile(
"<b>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_B_TAG_PATTERN = Pattern.compile(
"</b>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_I_TAG_PATTERN = Pattern.compile(
"<i>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_I_TAG_PATTERN = Pattern.compile(
"</i>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern
.compile("<blockquote>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern
.compile("</blockquote>", Pattern.CASE_INSENSITIVE);
private static final Pattern BR_TAG_PATTERN = Pattern.compile(
"<br */*>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_P_TAG_PATTERN = Pattern.compile(
"<p>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_P_TAG_PATTERN = Pattern.compile(
"</p>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern.compile(
"<pre>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern.compile(
"</pre>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_UL_TAG_PATTERN = Pattern.compile(
"<ul>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern.compile(
"</ul>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_OL_TAG_PATTERN = Pattern.compile(
"<ol>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern.compile(
"</ol>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_LI_TAG_PATTERN = Pattern.compile(
"<li>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern.compile(
"</li>", Pattern.CASE_INSENSITIVE);
private static final Pattern CLOSING_A_TAG_PATTERN = Pattern.compile(
"</a>", Pattern.CASE_INSENSITIVE);
private static final Pattern OPENING_A_TAG_PATTERN = Pattern.compile(
"<a href=.*?>", Pattern.CASE_INSENSITIVE);
private static final Pattern QUOTE_PATTERN = Pattern.compile(""",
Pattern.CASE_INSENSITIVE);
// ------------------------------------------------------------------------
/** Strip jsessionid off of a URL */
public static String stripJsessionId(String url) {
// Strip off jsessionid found in referer URL
int startPos = url.indexOf(";jsessionid=");
if (startPos != -1) {
int endPos = url.indexOf('?', startPos);
if (endPos == -1) {
url = url.substring(0, startPos);
} else {
url = url.substring(0, startPos)
+ url.substring(endPos, url.length());
}
}
return url;
}
// ------------------------------------------------------------------------
/**
* Escape, but do not replace HTML. The default behaviour is to escape
* ampersands.
*/
public static String escapeHTML(String s) {
return escapeHTML(s, true);
}
// ------------------------------------------------------------------------
/**
* Escape, but do not replace HTML.
*
* @param escapeAmpersand
* Optionally escape ampersands (&).
*/
public static String escapeHTML(String s, boolean escapeAmpersand) {
// got to do amp's first so we don't double escape
if (escapeAmpersand) {
s = StringUtils.replace(s, "&", "&");
}
s = StringUtils.replace(s, " ", " ");
s = StringUtils.replace(s, "\"", """);
s = StringUtils.replace(s, "<", "<");
s = StringUtils.replace(s, ">", ">");
return s;
}
public static String unescapeHTML(String str) {
return StringEscapeUtils.unescapeHtml4(str);
}
// ------------------------------------------------------------------------
/**
* Remove occurrences of html, defined as any text between the characters
* "<" and ">". Replace any HTML tags with a space.
*/
public static String removeHTML(String str) {
return removeHTML(str, true);
}
/**
* Remove occurrences of html, defined as any text between the characters
* "<" and ">". Optionally replace HTML tags with a space.
*
* @param str
* @param addSpace
* @return
*/
public static String removeHTML(String str, boolean addSpace) {
if (str == null) {
return "";
}
StringBuilder ret = new StringBuilder(str.length());
int start = 0;
int beginTag = str.indexOf('<');
int endTag = 0;
if (beginTag == -1) {
return str;
}
while (beginTag >= start) {
if (beginTag > 0) {
ret.append(str.substring(start, beginTag));
// replace each tag with a space (looks better)
if (addSpace) {
ret.append(" ");
}
}
endTag = str.indexOf('>', beginTag);
// if endTag found move "cursor" forward
if (endTag > -1) {
start = endTag + 1;
beginTag = str.indexOf('<', start);
}
// if no endTag found, get rest of str and break
else {
ret.append(str.substring(beginTag));
break;
}
}
// append everything after the last endTag
if (endTag > -1 && endTag + 1 < str.length()) {
ret.append(str.substring(endTag + 1));
}
return ret.toString().trim();
}
// ------------------------------------------------------------------------
/**
* Run both removeHTML and escapeHTML on a string.
*
* @param s
* String to be run through removeHTML and escapeHTML.
* @return String with HTML removed and HTML special characters escaped.
*/
public static String removeAndEscapeHTML(String s) {
if (s == null) {
return "";
} else {
return Utilities.escapeHTML(Utilities.removeHTML(s));
}
}
// ------------------------------------------------------------------------
/**
* Autoformat.
*/
public static String autoformat(String s) {
return StringUtils.replace(s, "\n", "<br />");
}
/**
* Code (stolen from Pebble) to add rel="nofollow" string to all links in
* HTML.
*/
public static String addNofollow(String html) {
if (html == null || html.length() == 0) {
return html;
}
Matcher m = mLinkPattern.matcher(html);
StringBuilder buf = new StringBuilder();
while (m.find()) {
int start = m.start();
int end = m.end();
String link = html.substring(start, end);
buf.append(html.substring(0, start));
if (link.contains("rel=\"nofollow\"")) {
buf.append(link.substring(0, link.length() - 1)
+ " rel=\"nofollow\">");
} else {
buf.append(link);
}
html = html.substring(end, html.length());
m = mLinkPattern.matcher(html);
}
buf.append(html);
return buf.toString();
}
// ------------------------------------------------------------------------
/**
* Replaces occurences of non-alphanumeric characters with an underscore.
*/
public static String replaceNonAlphanumeric(String str) {
return replaceNonAlphanumeric(str, '_');
}
// ------------------------------------------------------------------------
/**
* Replaces occurrences of non-alphanumeric characters with a supplied char.
*/
public static String replaceNonAlphanumeric(String str, char subst) {
StringBuilder ret = new StringBuilder(str.length());
char[] testChars = str.toCharArray();
for (int i = 0; i < testChars.length; i++) {
if (Character.isLetterOrDigit(testChars[i])) {
ret.append(testChars[i]);
} else {
ret.append(subst);
}
}
return ret.toString();
}
// ------------------------------------------------------------------------
/**
* Remove occurences of non-alphanumeric characters.
*/
public static String removeNonAlphanumeric(String str) {
StringBuilder ret = new StringBuilder(str.length());
char[] testChars = str.toCharArray();
for (int i = 0; i < testChars.length; i++) {
// MR: Allow periods in page links
if (Character.isLetterOrDigit(testChars[i]) || testChars[i] == '.') {
ret.append(testChars[i]);
}
}
return ret.toString();
}
// ------------------------------------------------------------------------
/** Convert string array to string with delimeters. */
public static String stringArrayToString(String[] stringArray, String delim) {
StringBuilder bldr = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
if (bldr.length() > 0) {
bldr.append(delim).append(stringArray[i]);
} else {
bldr.append(stringArray[i]);
}
}
return bldr.toString();
}
// ------------------------------------------------------------------------
/** Convert string array to string with delimeters. */
public static String stringListToString(List<String> stringList,
String delim) {
StringBuilder bldr = new StringBuilder();
for (String s : stringList) {
if (bldr.length() > 0) {
bldr.append(delim).append(s);
} else {
bldr.append(s);
}
}
return bldr.toString();
}
// --------------------------------------------------------------------------
/** Convert string with delimeters to string array. */
public static String[] stringToStringArray(String instr, String delim) {
return StringUtils.split(instr, delim);
}
// --------------------------------------------------------------------------
/** Convert string with delimiters to string list.
*/
public static List<String> stringToStringList(String instr, String delim) {
List<String> stringList = new ArrayList<>();
String[] str = StringUtils.split(instr, delim);
stringList.addAll(Arrays.asList(str));
return stringList;
}
// --------------------------------------------------------------------------
/** Convert string to integer array. */
public static int[] stringToIntArray(String instr, String delim) {
String[] str = StringUtils.split(instr, delim);
int intArray[] = new int[str.length];
int i = 0;
for (String string : str) {
int nInt = Integer.parseInt(string);
intArray[i++] = nInt;
}
return intArray;
}
// -------------------------------------------------------------------
/** Convert integer array to a string. */
public static String intArrayToString(int[] intArray) {
StringBuilder bldr = new StringBuilder();
for (int s : intArray) {
if (bldr.length() > 0) {
bldr.append(",").append(Integer.toString(s));
} else {
bldr.append(Integer.toString(s));
}
}
return bldr.toString();
}
// ------------------------------------------------------------------------
public static void copyFile(File from, File to) throws IOException {
InputStream in;
OutputStream out;
try {
in = new FileInputStream(from);
} catch (IOException ex) {
throw new IOException("Utilities.copyFile: opening input stream '"
+ from.getPath() + "', " + ex.getMessage());
}
try {
out = new FileOutputStream(to);
} catch (Exception ex) {
try {
in.close();
} catch (IOException ex1) {
}
throw new IOException("Utilities.copyFile: opening output stream '"
+ to.getPath() + "', " + ex.getMessage());
}
copyInputToOutput(in, out, from.length());
}
/**
* Reads an inputstream into a string
*/
public static String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
// ------------------------------------------------------------------------
/**
* Utility method to copy an input stream to an output stream. Wraps both
* streams in buffers. Ensures right numbers of bytes copied.
*/
public static void copyInputToOutput(InputStream input,
OutputStream output, long byteCount) throws IOException {
int bytes;
long length;
BufferedInputStream in = new BufferedInputStream(input);
BufferedOutputStream out = new BufferedOutputStream(output);
byte[] buffer;
buffer = new byte[RollerConstants.EIGHT_KB_IN_BYTES];
for (length = byteCount; length > 0;) {
bytes = (int) (length > RollerConstants.EIGHT_KB_IN_BYTES ? RollerConstants.EIGHT_KB_IN_BYTES : length);
try {
bytes = in.read(buffer, 0, bytes);
} catch (IOException ex) {
try {
in.close();
out.close();
} catch (IOException ex1) {
}
throw new IOException("Reading input stream, "
+ ex.getMessage());
}
if (bytes < 0) {
break;
}
length -= bytes;
try {
out.write(buffer, 0, bytes);
} catch (IOException ex) {
try {
in.close();
out.close();
} catch (IOException ex1) {
}
throw new IOException("Writing output stream, "
+ ex.getMessage());
}
}
try {
in.close();
out.close();
} catch (IOException ex) {
throw new IOException("Closing file streams, " + ex.getMessage());
}
}
// ------------------------------------------------------------------------
public static void copyInputToOutput(InputStream input, OutputStream output)
throws IOException {
BufferedInputStream in = new BufferedInputStream(input);
BufferedOutputStream out = new BufferedOutputStream(output);
byte buffer[] = new byte[RollerConstants.EIGHT_KB_IN_BYTES];
for (int count = 0; count != -1;) {
count = in.read(buffer, 0, RollerConstants.EIGHT_KB_IN_BYTES);
if (count != -1) {
out.write(buffer, 0, count);
}
}
try {
in.close();
out.close();
} catch (IOException ex) {
throw new IOException("Closing file streams, " + ex.getMessage());
}
}
/**
* Encode a string using algorithm specified in web.xml and return the
* resulting encrypted password. If exception, the plain credentials string
* is returned
*
* @param password
* Password or other credentials to use in authenticating this
* username
* @param algorithm
* Algorithm used to do the digest
*
* @return encypted password based on the algorithm.
*/
public static String encodePassword(String password, String algorithm) {
byte[] unencodedPassword = password.getBytes();
MessageDigest md;
try {
// first create an instance, given the provider
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
mLogger.error("Exception: " + e);
return password;
}
md.reset();
// call the update method one or more times
// (useful when you don't know the size of your data, eg. stream)
md.update(unencodedPassword);
// now calculate the hash
byte[] encodedPassword = md.digest();
StringBuilder buf = new StringBuilder();
for (int i = 0; i < encodedPassword.length; i++) {
if ((encodedPassword[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
}
return buf.toString();
}
/**
* Encode a string using Base64 encoding. Used when storing passwords as
* cookies.
*
* This is weak encoding in that anyone can use the decodeString routine to
* reverse the encoding.
*
* @param str
* String to encode
* @return String
* @throws IOException
*/
public static String encodeString(String str) throws IOException {
String encodedStr = new String(Base64.encodeBase64(str.getBytes()));
return (encodedStr.trim());
}
/**
* Decode a string using Base64 encoding.
*
* @param str
* String to decode
* @return decoded string
* @throws IOException
*/
public static String decodeString(String str) throws IOException {
String value = new String(Base64.decodeBase64(str.getBytes()));
return (value);
}
/**
* Strips HTML and truncates.
*/
public static String truncate(String str, int lower, int upper,
String appendToEnd) {
// strip markup from the string
String str2 = removeHTML(str, false);
// quickly adjust the upper if it is set lower than 'lower'
if (upper < lower) {
upper = lower;
}
// now determine if the string fits within the upper limit
// if it does, go straight to return, do not pass 'go' and collect $200
if (str2.length() > upper) {
// the magic location int
int loc;
// first we determine where the next space appears after lower
loc = str2.lastIndexOf(' ', upper);
// now we'll see if the location is greater than the lower limit
if (loc >= lower) {
// yes it was, so we'll cut it off here
str2 = str2.substring(0, loc);
} else {
// no it wasnt, so we'll cut it off at the upper limit
str2 = str2.substring(0, upper);
}
// the string was truncated, so we append the appendToEnd String
str2 = str2 + appendToEnd;
}
return str2;
}
/**
* This method based on code from the String taglib at Apache Jakarta:
* http:/
* /cvs.apache.org/viewcvs/jakarta-taglibs/string/src/org/apache/taglibs
* /string/util/StringW.java?rev=1.16&content-type=text/vnd.viewcvs-markup
* Copyright (c) 1999 The Apache Software Foundation. Author:
* timster@mac.com
*
* @param str
* @param lower
* @param upper
* @param appendToEnd
* @return
*/
public static String truncateNicely(String str, int lower, int upper,
String appendToEnd) {
// strip markup from the string
String str2 = removeHTML(str, false);
boolean diff = (str2.length() < str.length());
// quickly adjust the upper if it is set lower than 'lower'
if (upper < lower) {
upper = lower;
}
// now determine if the string fits within the upper limit
// if it does, go straight to return, do not pass 'go' and collect $200
if (str2.length() > upper) {
// the magic location int
int loc;
// first we determine where the next space appears after lower
loc = str2.lastIndexOf(' ', upper);
// now we'll see if the location is greater than the lower limit
if (loc >= lower) {
// yes it was, so we'll cut it off here
str2 = str2.substring(0, loc);
} else {
// no it wasnt, so we'll cut it off at the upper limit
str2 = str2.substring(0, upper);
loc = upper;
}
// HTML was removed from original str
if (diff) {
// location of last space in truncated string
loc = str2.lastIndexOf(' ', loc);
// get last "word" in truncated string (add 1 to loc to
// eliminate space
String str3 = str2.substring(loc + 1);
// find this fragment in original str, from 'loc' position
loc = str.indexOf(str3, loc) + str3.length();
// get truncated string from original str, given new 'loc'
str2 = str.substring(0, loc);
// get all the HTML from original str after loc
str3 = extractHTML(str.substring(loc));
// remove any tags which generate visible HTML
// This call is unecessary, all HTML has already been stripped
// str3 = removeVisibleHTMLTags(str3);
// append the appendToEnd String and
// add extracted HTML back onto truncated string
str = str2 + appendToEnd + str3;
} else {
// the string was truncated, so we append the appendToEnd String
str = str2 + appendToEnd;
}
}
return str;
}
public static String truncateText(String str, int lower, int upper,
String appendToEnd) {
// strip markup from the string
String str2 = removeHTML(str, false);
// quickly adjust the upper if it is set lower than 'lower'
if (upper < lower) {
upper = lower;
}
// now determine if the string fits within the upper limit
// if it does, go straight to return, do not pass 'go' and collect $200
if (str2.length() > upper) {
// the magic location int
int loc;
// first we determine where the next space appears after lower
loc = str2.lastIndexOf(' ', upper);
// now we'll see if the location is greater than the lower limit
if (loc >= lower) {
// yes it was, so we'll cut it off here
str2 = str2.substring(0, loc);
} else {
// no it wasnt, so we'll cut it off at the upper limit
str2 = str2.substring(0, upper);
}
// the string was truncated, so we append the appendToEnd String
str = str2 + appendToEnd;
}
return str;
}
/**
* @param str
* @return
*/
private static String stripLineBreaks(String str) {
// TODO: use a string buffer, ignore case !
str = str.replace("<br>", "");
str = str.replace("<br/>", "");
str = str.replace("<br />", "");
str = str.replace("<p></p>", "");
str = str.replace("<p/>", "");
str = str.replace("<p />", "");
return str;
}
/**
* Need need to get rid of any user-visible HTML tags once all text has been
* removed such as <BR>. This sounds like a better approach than
* removing all HTML tags and taking the chance to leave some tags
* un-closed.
*
* WARNING: this method has serious performance problems a
*
* @author Alexis Moussine-Pouchkine
* (alexis.moussine-pouchkine@france.sun.com)
* @author Lance Lavandowska
* @param str
* the String object to modify
* @return the new String object without the HTML "visible" tags
*/
private static String removeVisibleHTMLTags(String str) {
str = stripLineBreaks(str);
StringBuilder result = new StringBuilder(str);
StringBuilder lcresult = new StringBuilder(str.toLowerCase());
// <img should take care of smileys, others to add?
String[] visibleTags = { "<img" };
int stringIndex;
for (int j = 0; j < visibleTags.length; j++) {
while ((stringIndex = lcresult.indexOf(visibleTags[j])) != -1) {
if (visibleTags[j].endsWith(">")) {
result.delete(stringIndex,
stringIndex + visibleTags[j].length());
lcresult.delete(stringIndex,
stringIndex + visibleTags[j].length());
} else {
// need to delete everything up until next closing '>', for
// <img for instance
int endIndex = result.indexOf(">", stringIndex);
if (endIndex > -1) {
// only delete it if we find the end! If we don't the
// HTML may be messed up, but we
// can't safely delete anything.
result.delete(stringIndex, endIndex + 1);
lcresult.delete(stringIndex, endIndex + 1);
}
}
}
}
// TODO: This code is buggy by nature. It doesn't deal with nesting of
// tags properly.
// remove certain elements with open & close tags, more available?
String[] openCloseTags = { "li", "a", "div", "h1", "h2", "h3", "h4" };
for (int j = 0; j < openCloseTags.length; j++) {
// could this be better done with a regular expression?
String closeTag = "</" + openCloseTags[j] + ">";
int lastStringIndex = 0;
while ((stringIndex = lcresult.indexOf("<" + openCloseTags[j],
lastStringIndex)) > -1) {
lastStringIndex = stringIndex;
// Try to find the matching closing tag (ignores possible
// nesting!)
int endIndex = lcresult.indexOf(closeTag, stringIndex);
if (endIndex > -1) {
// If we found it delete it.
result.delete(stringIndex, endIndex + closeTag.length());
lcresult.delete(stringIndex, endIndex + closeTag.length());
} else {
// Try to see if it is a self-closed empty content tag, i.e.
// closed with />.
endIndex = lcresult.indexOf(">", stringIndex);
int nextStart = lcresult.indexOf("<", stringIndex + 1);
if (endIndex > stringIndex
&& lcresult.charAt(endIndex - 1) == '/'
&& (endIndex < nextStart || nextStart == -1)) {
// Looks like it, so remove it.
result.delete(stringIndex, endIndex + 1);
lcresult.delete(stringIndex, endIndex + 1);
}
}
}
}
return result.toString();
}
/**
* Extract (keep) JUST the HTML from the String.
*
* @param str
* @return
*/
public static String extractHTML(String str) {
if (str == null) {
return "";
}
StringBuilder ret = new StringBuilder(str.length());
int start = 0;
int beginTag = str.indexOf('<');
int endTag = 0;
if (beginTag == -1) {
return str;
}
while (beginTag >= start) {
endTag = str.indexOf('>', beginTag);
// if endTag found, keep tag
if (endTag > -1) {
ret.append(str.substring(beginTag, endTag + 1));
// move start forward and find another tag
start = endTag + 1;
beginTag = str.indexOf('<', start);
}
// if no endTag found, break
else {
break;
}
}
return ret.toString();
}
public static String hexEncode(String str) {
if (StringUtils.isEmpty(str)) {
return str;
}
return RegexUtil.encode(str);
}
public static String encodeEmail(String str) {
return str != null ? RegexUtil.encodeEmail(str) : null;
}
/**
* @param string
* @return
*/
public static int stringToInt(String string) {
try {
return Integer.valueOf(string);
} catch (NumberFormatException e) {
mLogger.debug("Invalid Integer:" + string);
}
return 0;
}
/**
* Convert a byte array into a Base64 string (as used in mime formats)
*/
public static String toBase64(byte[] aValue) {
final String strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int byte1;
int byte2;
int byte3;
int iByteLen = aValue.length;
StringBuilder tt = new StringBuilder();
for (int i = 0; i < iByteLen; i += 3) {
boolean bByte2 = (i + 1) < iByteLen;
boolean bByte3 = (i + 2) < iByteLen;
byte1 = aValue[i] & 0xFF;
byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
tt.append(strBase64Chars.charAt(byte1 / 4));
tt.append(strBase64Chars
.charAt((byte2 / 16) + ((byte1 & 0x3) * 16)));
tt.append(((bByte2) ? strBase64Chars.charAt((byte3 / 64)
+ ((byte2 & 0xF) * 4)) : '='));
tt.append(((bByte3) ? strBase64Chars.charAt(byte3 & 0x3F) : '='));
}
return tt.toString();
}
/**
* @param tag
* @return
*/
public static String stripInvalidTagCharacters(String tag) {
if (tag == null) {
throw new NullPointerException();
}
StringBuilder sb = new StringBuilder();
char[] charArray = tag.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
// fast-path exclusions quotes and commas are obvious
// 34 = double-quote, 44 = comma
switch (c) {
case 34:
case 44:
continue;
}
if ((33 <= c && c <= 126) || Character.isUnicodeIdentifierPart(c)
|| Character.isUnicodeIdentifierStart(c)) {
sb.append(charArray[i]);
}
}
return sb.toString();
}
public static String normalizeTag(String tag, Locale locale) {
tag = Utilities.stripInvalidTagCharacters(tag);
return locale == null ? tag.toLowerCase() : tag.toLowerCase(locale);
}
/**
* @param tags String holding space separated list of tags
* @return List of strings, one string for each tag
*/
public static List<String> splitStringAsTags(String tags) {
String[] tagsarr = StringUtils.split(tags, TAG_SPLIT_CHARS);
if (tagsarr == null) {
return Collections.emptyList();
}
return Arrays.asList(tagsarr);
}
/**
* Transforms the given String into a subset of HTML displayable on a web
* page. The subset includes <b>, <i>, <p>, <br>,
* <pre> and <a href> (and their corresponding end tags).
*
* @param s
* the String to transform
* @return the transformed String
*/
public static String transformToHTMLSubset(String s) {
if (s == null) {
return null;
}
s = replace(s, OPENING_B_TAG_PATTERN, "<b>");
s = replace(s, CLOSING_B_TAG_PATTERN, "</b>");
s = replace(s, OPENING_I_TAG_PATTERN, "<i>");
s = replace(s, CLOSING_I_TAG_PATTERN, "</i>");
s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>");
s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>");
s = replace(s, BR_TAG_PATTERN, "<br />");
s = replace(s, OPENING_P_TAG_PATTERN, "<p>");
s = replace(s, CLOSING_P_TAG_PATTERN, "</p>");
s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>");
s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>");
s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>");
s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>");
s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>");
s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>");
s = replace(s, OPENING_LI_TAG_PATTERN, "<li>");
s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>");
s = replace(s, QUOTE_PATTERN, "\"");
// HTTP links
s = replace(s, CLOSING_A_TAG_PATTERN, "</a>");
Matcher m = OPENING_A_TAG_PATTERN.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
String link = s.substring(start, end);
link = "<" + link.substring(4, link.length() - 4) + ">";
s = s.substring(0, start) + link + s.substring(end, s.length());
m = OPENING_A_TAG_PATTERN.matcher(s);
}
// escaped angle brackets
s = s.replace("&lt;", "<");
s = s.replace("&gt;", ">");
s = s.replace("&#", "&#");
return s;
}
private static String replace(String string, Pattern pattern,
String replacement) {
Matcher m = pattern.matcher(string);
return m.replaceAll(replacement);
}
public static String getContentTypeFromFileName(String fileName) {
FileTypeMap map = FileTypeMap.getDefaultFileTypeMap();
// TODO: figure out why PNG is missing from Java MIME types
if (map instanceof MimetypesFileTypeMap) {
try {
((MimetypesFileTypeMap) map).addMimeTypes("image/png png PNG");
} catch (Exception ignored) {
}
}
return map.getContentType(fileName);
}
/**
* Validate the form of an email address.
*
* <P>
* Return <tt>true</tt> only if
* <ul>
* <li> <tt>aEmailAddress</tt> can successfully construct an
* {@link javax.mail.internet.InternetAddress}
* <li>when parsed with "@" as delimiter, <tt>aEmailAddress</tt> contains
* two tokens which satisfy
* </ul>
* <P>
* The second condition arises since local email addresses, simply of the
* form "<tt>albert</tt>", for example, are valid for
* {@link javax.mail.internet.InternetAddress}, but almost always undesired.
*/
public static boolean isValidEmailAddress(String aEmailAddress) {
if (aEmailAddress == null) {
return false;
}
boolean result = true;
try {
// See if its valid
new InternetAddress(aEmailAddress);
if (!hasNameAndDomain(aEmailAddress)) {
result = false;
}
} catch (AddressException ex) {
result = false;
}
return result;
}
/**
* Checks for name and domain.
*
* @param aEmailAddress
* the a email address
* @return true, if successful
*/
private static boolean hasNameAndDomain(String aEmailAddress) {
String[] tokens = aEmailAddress.split("@");
return tokens.length == 2 && StringUtils.isNotEmpty(tokens[0])
&& StringUtils.isNotEmpty(tokens[1]);
}
}
|
apache/kafka | 38,116 | streams/src/test/java/org/apache/kafka/streams/processor/internals/ProcessorContextImplTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.streams.processor.internals;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.StreamsConfig.InternalConfig;
import org.apache.kafka.streams.kstream.Windowed;
import org.apache.kafka.streams.processor.PunctuationType;
import org.apache.kafka.streams.processor.StateStore;
import org.apache.kafka.streams.processor.TaskId;
import org.apache.kafka.streams.processor.To;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.processor.internals.Task.TaskType;
import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
import org.apache.kafka.streams.query.Position;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.SessionStore;
import org.apache.kafka.streams.state.TimestampedKeyValueStore;
import org.apache.kafka.streams.state.TimestampedWindowStore;
import org.apache.kafka.streams.state.ValueAndTimestamp;
import org.apache.kafka.streams.state.WindowStore;
import org.apache.kafka.streams.state.WindowStoreIterator;
import org.apache.kafka.streams.state.internals.PositionSerde;
import org.apache.kafka.streams.state.internals.ThreadCache;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static java.util.Arrays.asList;
import static org.apache.kafka.common.utils.Utils.mkEntry;
import static org.apache.kafka.common.utils.Utils.mkMap;
import static org.apache.kafka.streams.processor.internals.ProcessorContextImpl.BYTEARRAY_VALUE_SERIALIZER;
import static org.apache.kafka.streams.processor.internals.ProcessorContextImpl.BYTES_KEY_SERIALIZER;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings("unchecked")
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
public class ProcessorContextImplTest {
private ProcessorContextImpl context;
private final StreamsConfig streamsConfig = streamsConfigMock();
@Mock
private RecordCollector recordCollector;
@Mock
private ProcessorStateManager stateManager;
private static final String KEY = "key";
private static final Bytes KEY_BYTES = Bytes.wrap(KEY.getBytes());
private static final long VALUE = 42L;
private static final byte[] VALUE_BYTES = String.valueOf(VALUE).getBytes();
private static final long TIMESTAMP = 21L;
private static final long STREAM_TIME = 50L;
private static final ValueAndTimestamp<Long> VALUE_AND_TIMESTAMP = ValueAndTimestamp.make(42L, 21L);
private static final String STORE_NAME = "underlying-store";
private static final String REGISTERED_STORE_NAME = "registered-store";
private static final TopicPartition CHANGELOG_PARTITION = new TopicPartition("store-changelog", 1);
private boolean flushExecuted = false;
private boolean putExecuted = false;
private boolean putWithTimestampExecuted;
private boolean putIfAbsentExecuted = false;
private boolean putAllExecuted = false;
private boolean deleteExecuted = false;
private boolean removeExecuted = false;
@Mock
private KeyValueIterator<String, Long> rangeIter;
@Mock
private KeyValueIterator<String, ValueAndTimestamp<Long>> timestampedRangeIter;
@Mock
private KeyValueIterator<String, Long> allIter;
@Mock
private KeyValueIterator<String, ValueAndTimestamp<Long>> timestampedAllIter;
@SuppressWarnings("rawtypes")
@Mock
private WindowStoreIterator windowStoreIter;
private final List<KeyValueIterator<Windowed<String>, Long>> iters = new ArrayList<>(7);
private final List<KeyValueIterator<Windowed<String>, ValueAndTimestamp<Long>>> timestampedIters = new ArrayList<>(7);
private void foreachSetUp() {
for (int i = 0; i < 7; i++) {
iters.add(i, mock(KeyValueIterator.class));
timestampedIters.add(i, mock(KeyValueIterator.class));
}
}
private ProcessorContextImpl getStandbyContext() {
final ProcessorStateManager stateManager = mock(ProcessorStateManager.class);
when(stateManager.taskType()).thenReturn(TaskType.STANDBY);
return buildProcessorContextImpl(streamsConfig, stateManager);
}
@Test
public void globalKeyValueStoreShouldBeReadOnly() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final KeyValueStore<String, Long> keyValueStoreMock = mock(KeyValueStore.class);
when(stateManager.globalStore("GlobalKeyValueStore")).thenAnswer(answer -> keyValueStoreMock(keyValueStoreMock));
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("GlobalKeyValueStore", (Consumer<KeyValueStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
checkThrowsUnsupportedOperation(store::flush, "flush()");
checkThrowsUnsupportedOperation(() -> store.put("1", 1L), "put()");
checkThrowsUnsupportedOperation(() -> store.putIfAbsent("1", 1L), "putIfAbsent()");
checkThrowsUnsupportedOperation(() -> store.putAll(Collections.emptyList()), "putAll()");
checkThrowsUnsupportedOperation(() -> store.delete("1"), "delete()");
assertEquals((Long) VALUE, store.get(KEY));
assertEquals(rangeIter, store.range("one", "two"));
assertEquals(allIter, store.all());
assertEquals(VALUE, store.approximateNumEntries());
});
}
@Test
public void globalTimestampedKeyValueStoreShouldBeReadOnly() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final TimestampedKeyValueStore<String, Long> timestampedKeyValueStoreMock = mock(TimestampedKeyValueStore.class);
when(stateManager.globalStore("GlobalTimestampedKeyValueStore")).thenAnswer(answer -> timestampedKeyValueStoreMock(timestampedKeyValueStoreMock));
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("GlobalTimestampedKeyValueStore", (Consumer<TimestampedKeyValueStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
checkThrowsUnsupportedOperation(store::flush, "flush()");
checkThrowsUnsupportedOperation(() -> store.put("1", ValueAndTimestamp.make(1L, 2L)), "put()");
checkThrowsUnsupportedOperation(() -> store.putIfAbsent("1", ValueAndTimestamp.make(1L, 2L)), "putIfAbsent()");
checkThrowsUnsupportedOperation(() -> store.putAll(Collections.emptyList()), "putAll()");
checkThrowsUnsupportedOperation(() -> store.delete("1"), "delete()");
assertEquals(VALUE_AND_TIMESTAMP, store.get(KEY));
assertEquals(timestampedRangeIter, store.range("one", "two"));
assertEquals(timestampedAllIter, store.all());
assertEquals(VALUE, store.approximateNumEntries());
});
}
@Test
public void globalWindowStoreShouldBeReadOnly() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final WindowStore<String, Long> windowStore = mock(WindowStore.class);
when(stateManager.globalStore("GlobalWindowStore")).thenAnswer(answer -> windowStoreMock(windowStore));
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("GlobalWindowStore", (Consumer<WindowStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
checkThrowsUnsupportedOperation(store::flush, "flush()");
checkThrowsUnsupportedOperation(() -> store.put("1", 1L, 1L), "put()");
assertEquals(iters.get(0), store.fetchAll(0L, 0L));
assertEquals(windowStoreIter, store.fetch(KEY, 0L, 1L));
assertEquals(iters.get(1), store.fetch(KEY, KEY, 0L, 1L));
assertEquals((Long) VALUE, store.fetch(KEY, 1L));
assertEquals(iters.get(2), store.all());
});
}
@Test
public void globalTimestampedWindowStoreShouldBeReadOnly() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final TimestampedWindowStore<String, Long> windowStore = mock(TimestampedWindowStore.class);
when(stateManager.globalStore("GlobalTimestampedWindowStore")).thenAnswer(answer -> timestampedWindowStoreMock(windowStore));
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("GlobalTimestampedWindowStore", (Consumer<TimestampedWindowStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
checkThrowsUnsupportedOperation(store::flush, "flush()");
checkThrowsUnsupportedOperation(() -> store.put("1", ValueAndTimestamp.make(1L, 1L), 1L), "put() [with timestamp]");
assertEquals(timestampedIters.get(0), store.fetchAll(0L, 0L));
assertEquals(windowStoreIter, store.fetch(KEY, 0L, 1L));
assertEquals(timestampedIters.get(1), store.fetch(KEY, KEY, 0L, 1L));
assertEquals(VALUE_AND_TIMESTAMP, store.fetch(KEY, 1L));
assertEquals(timestampedIters.get(2), store.all());
});
}
@Test
public void globalSessionStoreShouldBeReadOnly() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final SessionStore<String, Long> sessionStore = mock(SessionStore.class);
when(stateManager.globalStore("GlobalSessionStore")).thenAnswer(answer -> sessionStoreMock(sessionStore));
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("GlobalSessionStore", (Consumer<SessionStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
checkThrowsUnsupportedOperation(store::flush, "flush()");
checkThrowsUnsupportedOperation(() -> store.remove(null), "remove()");
checkThrowsUnsupportedOperation(() -> store.put(null, null), "put()");
assertEquals(iters.get(3), store.findSessions(KEY, 1L, 2L));
assertEquals(iters.get(4), store.findSessions(KEY, KEY, 1L, 2L));
assertEquals(iters.get(5), store.fetch(KEY));
assertEquals(iters.get(6), store.fetch(KEY, KEY));
});
}
@Test
public void localKeyValueStoreShouldNotAllowInitOrClose() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final KeyValueStore<String, Long> keyValueStoreMock = mock(KeyValueStore.class);
when(stateManager.store("LocalKeyValueStore")).thenAnswer(answer -> keyValueStoreMock(keyValueStoreMock));
mockStateStoreFlush(keyValueStoreMock);
mockKeyValueStoreOperation(keyValueStoreMock);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("LocalKeyValueStore", (Consumer<KeyValueStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
store.flush();
assertTrue(flushExecuted);
store.put("1", 1L);
assertTrue(putExecuted);
store.putIfAbsent("1", 1L);
assertTrue(putIfAbsentExecuted);
store.putAll(Collections.emptyList());
assertTrue(putAllExecuted);
store.delete("1");
assertTrue(deleteExecuted);
assertEquals((Long) VALUE, store.get(KEY));
assertEquals(rangeIter, store.range("one", "two"));
assertEquals(allIter, store.all());
assertEquals(VALUE, store.approximateNumEntries());
});
}
@Test
public void localTimestampedKeyValueStoreShouldNotAllowInitOrClose() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final TimestampedKeyValueStore<String, Long> timestampedKeyValueStoreMock = mock(TimestampedKeyValueStore.class);
when(stateManager.store("LocalTimestampedKeyValueStore"))
.thenAnswer(answer -> timestampedKeyValueStoreMock(timestampedKeyValueStoreMock));
mockTimestampedKeyValueOperation(timestampedKeyValueStoreMock);
mockStateStoreFlush(timestampedKeyValueStoreMock);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("LocalTimestampedKeyValueStore", (Consumer<TimestampedKeyValueStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
store.flush();
assertTrue(flushExecuted);
store.put("1", ValueAndTimestamp.make(1L, 2L));
assertTrue(putExecuted);
store.putIfAbsent("1", ValueAndTimestamp.make(1L, 2L));
assertTrue(putIfAbsentExecuted);
store.putAll(Collections.emptyList());
assertTrue(putAllExecuted);
store.delete("1");
assertTrue(deleteExecuted);
assertEquals(VALUE_AND_TIMESTAMP, store.get(KEY));
assertEquals(timestampedRangeIter, store.range("one", "two"));
assertEquals(timestampedAllIter, store.all());
assertEquals(VALUE, store.approximateNumEntries());
});
}
@Test
public void localWindowStoreShouldNotAllowInitOrClose() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final WindowStore<String, Long> windowStore = mock(WindowStore.class);
when(stateManager.store("LocalWindowStore")).thenAnswer(answer -> windowStoreMock(windowStore));
mockStateStoreFlush(windowStore);
doAnswer(answer -> {
putExecuted = true;
return null;
}).when(windowStore).put(anyString(), anyLong(), anyLong());
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("LocalWindowStore", (Consumer<WindowStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
store.flush();
assertTrue(flushExecuted);
store.put("1", 1L, 1L);
assertTrue(putExecuted);
assertEquals(iters.get(0), store.fetchAll(0L, 0L));
assertEquals(windowStoreIter, store.fetch(KEY, 0L, 1L));
assertEquals(iters.get(1), store.fetch(KEY, KEY, 0L, 1L));
assertEquals((Long) VALUE, store.fetch(KEY, 1L));
assertEquals(iters.get(2), store.all());
});
}
@Test
public void localTimestampedWindowStoreShouldNotAllowInitOrClose() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final TimestampedWindowStore<String, Long> windowStore = mock(TimestampedWindowStore.class);
when(stateManager.store("LocalTimestampedWindowStore")).thenAnswer(answer -> timestampedWindowStoreMock(windowStore));
mockStateStoreFlush(windowStore);
doAnswer(answer -> {
putExecuted = true;
return null;
}).doAnswer(answer -> {
putWithTimestampExecuted = true;
return null;
}).when(windowStore).put(anyString(), any(ValueAndTimestamp.class), anyLong());
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("LocalTimestampedWindowStore", (Consumer<TimestampedWindowStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
store.flush();
assertTrue(flushExecuted);
store.put("1", ValueAndTimestamp.make(1L, 1L), 1L);
assertTrue(putExecuted);
store.put("1", ValueAndTimestamp.make(1L, 1L), 1L);
assertTrue(putWithTimestampExecuted);
assertEquals(timestampedIters.get(0), store.fetchAll(0L, 0L));
assertEquals(windowStoreIter, store.fetch(KEY, 0L, 1L));
assertEquals(timestampedIters.get(1), store.fetch(KEY, KEY, 0L, 1L));
assertEquals(VALUE_AND_TIMESTAMP, store.fetch(KEY, 1L));
assertEquals(timestampedIters.get(2), store.all());
});
}
@Test
public void localSessionStoreShouldNotAllowInitOrClose() {
foreachSetUp();
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.globalStore(anyString())).thenReturn(null);
final SessionStore<String, Long> sessionStore = mock(SessionStore.class);
when(stateManager.store("LocalSessionStore")).thenAnswer(answer -> sessionStoreMock(sessionStore));
mockStateStoreFlush(sessionStore);
doAnswer(answer -> {
putExecuted = true;
return null;
}).when(sessionStore).put(any(), any());
doAnswer(answer -> {
removeExecuted = true;
return null;
}).when(sessionStore).remove(any());
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
doTest("LocalSessionStore", (Consumer<SessionStore<String, Long>>) store -> {
verifyStoreCannotBeInitializedOrClosed(store);
store.flush();
assertTrue(flushExecuted);
store.remove(null);
assertTrue(removeExecuted);
store.put(null, null);
assertTrue(putExecuted);
assertEquals(iters.get(3), store.findSessions(KEY, 1L, 2L));
assertEquals(iters.get(4), store.findSessions(KEY, KEY, 1L, 2L));
assertEquals(iters.get(5), store.fetch(KEY));
assertEquals(iters.get(6), store.fetch(KEY, KEY));
});
}
@Test
public void shouldNotSendRecordHeadersToChangelogTopic() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.registeredChangelogPartitionFor(REGISTERED_STORE_NAME)).thenReturn(CHANGELOG_PARTITION);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
final StreamTask task1 = mock(StreamTask.class);
context.transitionToActive(task1, recordCollector, null);
context.logChange(REGISTERED_STORE_NAME, KEY_BYTES, VALUE_BYTES, TIMESTAMP, Position.emptyPosition());
verify(recordCollector).send(
CHANGELOG_PARTITION.topic(),
KEY_BYTES,
VALUE_BYTES,
null,
CHANGELOG_PARTITION.partition(),
TIMESTAMP,
BYTES_KEY_SERIALIZER,
BYTEARRAY_VALUE_SERIALIZER,
null,
null);
}
@Test
public void shouldSendRecordHeadersToChangelogTopicWhenConsistencyEnabled() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
when(stateManager.registeredChangelogPartitionFor(REGISTERED_STORE_NAME)).thenReturn(CHANGELOG_PARTITION);
final Position position = Position.emptyPosition();
final Headers headers = new RecordHeaders();
headers.add(ChangelogRecordDeserializationHelper.CHANGELOG_VERSION_HEADER_RECORD_CONSISTENCY);
headers.add(new RecordHeader(ChangelogRecordDeserializationHelper.CHANGELOG_POSITION_HEADER_KEY,
PositionSerde.serialize(position).array()));
final StreamTask task1 = mock(StreamTask.class);
context = buildProcessorContextImpl(streamsConfigWithConsistencyMock(), stateManager);
context.transitionToActive(task1, recordCollector, null);
context.logChange(REGISTERED_STORE_NAME, KEY_BYTES, VALUE_BYTES, TIMESTAMP, position);
verify(recordCollector).send(
CHANGELOG_PARTITION.topic(),
KEY_BYTES,
VALUE_BYTES,
headers,
CHANGELOG_PARTITION.partition(),
TIMESTAMP,
BYTES_KEY_SERIALIZER,
BYTEARRAY_VALUE_SERIALIZER,
null,
null);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnLogChange() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.logChange("Store", Bytes.wrap("k".getBytes()), null, 0L, Position.emptyPosition())
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnGetStateStore() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.getStateStore("store")
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnForward() {
context = getStandbyContext();
context.recordContext = mock(ProcessorRecordContext.class);
assertThrows(
UnsupportedOperationException.class,
() -> context.forward("key", "value")
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnForwardWithTo() {
context = getStandbyContext();
context.recordContext = mock(ProcessorRecordContext.class);
assertThrows(
UnsupportedOperationException.class,
() -> context.forward("key", "value", To.child("child-name"))
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnCommit() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.commit()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnSchedule() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.schedule(Duration.ofMillis(100L), PunctuationType.STREAM_TIME, t -> { })
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnTopic() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.topic()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnPartition() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.partition()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnOffset() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.offset()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnTimestamp() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.timestamp()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnCurrentNode() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.currentNode()
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnSetRecordContext() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.setRecordContext(mock(ProcessorRecordContext.class))
);
}
@Test
public void shouldThrowUnsupportedOperationExceptionOnRecordContext() {
context = getStandbyContext();
assertThrows(
UnsupportedOperationException.class,
() -> context.recordContext()
);
}
@Test
public void shouldMatchStreamTime() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
when(task.streamTime()).thenReturn(STREAM_TIME);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
assertEquals(STREAM_TIME, context.currentStreamTimeMs());
}
@Test
public void shouldAddAndGetProcessorKeyValue() {
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
context = buildProcessorContextImpl(streamsConfig, stateManager);
final StreamTask task = mock(StreamTask.class);
context.transitionToActive(task, null, null);
mockProcessorNodeWithLocalKeyValueStore();
context.addProcessorMetadataKeyValue("key1", 100L);
final Long value = context.processorMetadataForKey("key1");
assertEquals(100L, value.longValue());
final Long noValue = context.processorMetadataForKey("nokey");
assertNull(noValue);
}
@Test
public void shouldSetAndGetProcessorMetaData() {
context = buildProcessorContextImpl(streamsConfig, stateManager);
mockProcessorNodeWithLocalKeyValueStore();
final ProcessorMetadata emptyMetadata = new ProcessorMetadata();
context.setProcessorMetadata(emptyMetadata);
assertEquals(emptyMetadata, context.processorMetadata());
final ProcessorMetadata metadata = new ProcessorMetadata(
mkMap(
mkEntry("key1", 10L),
mkEntry("key2", 100L)
)
);
context.setProcessorMetadata(metadata);
assertEquals(10L, context.processorMetadataForKey("key1").longValue());
assertEquals(100L, context.processorMetadataForKey("key2").longValue());
assertThrows(NullPointerException.class, () -> context.setProcessorMetadata(null));
}
private void mockProcessorNodeWithLocalKeyValueStore() {
context.setCurrentNode(
new ProcessorNode<>(
"fake",
(org.apache.kafka.streams.processor.api.Processor<String, Long, Object, Object>) null,
new HashSet<>(
asList(
"LocalKeyValueStore",
"LocalTimestampedKeyValueStore",
"LocalWindowStore",
"LocalTimestampedWindowStore",
"LocalSessionStore"
)
)
)
);
}
private ProcessorContextImpl buildProcessorContextImpl(final StreamsConfig streamsConfig, final ProcessorStateManager stateManager) {
return new ProcessorContextImpl(
mock(TaskId.class),
streamsConfig,
stateManager,
mock(StreamsMetricsImpl.class),
mock(ThreadCache.class)
);
}
private KeyValueStore<String, Long> keyValueStoreMock(final KeyValueStore<String, Long> keyValueStoreMock) {
initStateStoreMock(keyValueStoreMock);
when(keyValueStoreMock.get(KEY)).thenReturn(VALUE);
when(keyValueStoreMock.approximateNumEntries()).thenReturn(VALUE);
when(keyValueStoreMock.range("one", "two")).thenReturn(rangeIter);
when(keyValueStoreMock.all()).thenReturn(allIter);
return keyValueStoreMock;
}
private void mockKeyValueStoreOperation(final KeyValueStore<String, Long> keyValueStoreMock) {
doAnswer(answer -> {
putExecuted = true;
return null;
}).when(keyValueStoreMock).put(anyString(), anyLong());
doAnswer(answer -> {
putIfAbsentExecuted = true;
return null;
}).when(keyValueStoreMock).putIfAbsent(anyString(), anyLong());
doAnswer(answer -> {
putAllExecuted = true;
return null;
}).when(keyValueStoreMock).putAll(any(List.class));
doAnswer(answer -> {
deleteExecuted = true;
return null;
}).when(keyValueStoreMock).delete(anyString());
}
private TimestampedKeyValueStore<String, Long> timestampedKeyValueStoreMock(final TimestampedKeyValueStore<String, Long> timestampedKeyValueStoreMock) {
initStateStoreMock(timestampedKeyValueStoreMock);
when(timestampedKeyValueStoreMock.get(KEY)).thenReturn(VALUE_AND_TIMESTAMP);
when(timestampedKeyValueStoreMock.approximateNumEntries()).thenReturn(VALUE);
when(timestampedKeyValueStoreMock.range("one", "two")).thenReturn(timestampedRangeIter);
when(timestampedKeyValueStoreMock.all()).thenReturn(timestampedAllIter);
return timestampedKeyValueStoreMock;
}
private void mockTimestampedKeyValueOperation(final TimestampedKeyValueStore<String, Long> timestampedKeyValueStoreMock) {
doAnswer(answer -> {
putExecuted = true;
return null;
}).when(timestampedKeyValueStoreMock).put(anyString(), any(ValueAndTimestamp.class));
doAnswer(answer -> {
putIfAbsentExecuted = true;
return null;
}).when(timestampedKeyValueStoreMock).putIfAbsent(anyString(), any(ValueAndTimestamp.class));
doAnswer(answer -> {
putAllExecuted = true;
return null;
}).when(timestampedKeyValueStoreMock).putAll(any(List.class));
doAnswer(answer -> {
deleteExecuted = true;
return null;
}).when(timestampedKeyValueStoreMock).delete(anyString());
}
private WindowStore<String, Long> windowStoreMock(final WindowStore<String, Long> windowStore) {
initStateStoreMock(windowStore);
when(windowStore.fetchAll(anyLong(), anyLong())).thenReturn(iters.get(0));
when(windowStore.fetch(anyString(), anyString(), anyLong(), anyLong())).thenReturn(iters.get(1));
when(windowStore.fetch(anyString(), anyLong(), anyLong())).thenReturn(windowStoreIter);
when(windowStore.fetch(anyString(), anyLong())).thenReturn(VALUE);
when(windowStore.all()).thenReturn(iters.get(2));
return windowStore;
}
private TimestampedWindowStore<String, Long> timestampedWindowStoreMock(final TimestampedWindowStore<String, Long> windowStore) {
initStateStoreMock(windowStore);
when(windowStore.fetchAll(anyLong(), anyLong())).thenReturn(timestampedIters.get(0));
when(windowStore.fetch(anyString(), anyString(), anyLong(), anyLong())).thenReturn(timestampedIters.get(1));
when(windowStore.fetch(anyString(), anyLong(), anyLong())).thenReturn(windowStoreIter);
when(windowStore.fetch(anyString(), anyLong())).thenReturn(VALUE_AND_TIMESTAMP);
when(windowStore.all()).thenReturn(timestampedIters.get(2));
return windowStore;
}
private SessionStore<String, Long> sessionStoreMock(final SessionStore<String, Long> sessionStore) {
initStateStoreMock(sessionStore);
when(sessionStore.findSessions(anyString(), anyLong(), anyLong())).thenReturn(iters.get(3));
when(sessionStore.findSessions(anyString(), anyString(), anyLong(), anyLong())).thenReturn(iters.get(4));
when(sessionStore.fetch(anyString())).thenReturn(iters.get(5));
when(sessionStore.fetch(anyString(), anyString())).thenReturn(iters.get(6));
return sessionStore;
}
private StreamsConfig streamsConfigMock() {
final StreamsConfig streamsConfig = mock(StreamsConfig.class);
when(streamsConfig.originals()).thenReturn(Collections.emptyMap());
when(streamsConfig.values()).thenReturn(Collections.emptyMap());
when(streamsConfig.getString(StreamsConfig.APPLICATION_ID_CONFIG)).thenReturn("add-id");
return streamsConfig;
}
private StreamsConfig streamsConfigWithConsistencyMock() {
final StreamsConfig streamsConfig = mock(StreamsConfig.class);
final Map<String, Object> myValues = new HashMap<>();
myValues.put(InternalConfig.IQ_CONSISTENCY_OFFSET_VECTOR_ENABLED, true);
when(streamsConfig.originals()).thenReturn(myValues);
when(streamsConfig.values()).thenReturn(Collections.emptyMap());
when(streamsConfig.getString(StreamsConfig.APPLICATION_ID_CONFIG)).thenReturn("add-id");
return streamsConfig;
}
private void initStateStoreMock(final StateStore stateStore) {
when(stateStore.name()).thenReturn(STORE_NAME);
when(stateStore.persistent()).thenReturn(true);
when(stateStore.isOpen()).thenReturn(true);
}
private void mockStateStoreFlush(final StateStore stateStore) {
doAnswer(answer -> {
flushExecuted = true;
return null;
}).when(stateStore).flush();
}
@SuppressWarnings("rawtypes")
private <T extends StateStore> void doTest(final String name, final Consumer<T> checker) {
final Processor<String, Long, String, Long> processor = new Processor<>() {
@Override
public void init(final ProcessorContext<String, Long> context) {
final T store = context.getStateStore(name);
checker.accept(store);
}
@Override
public void process(final Record<String, Long> record) {
//No-op.
}
@Override
public void close() {
//No-op.
}
};
processor.init((ProcessorContext) context);
}
private void verifyStoreCannotBeInitializedOrClosed(final StateStore store) {
assertEquals(STORE_NAME, store.name());
assertTrue(store.persistent());
assertTrue(store.isOpen());
checkThrowsUnsupportedOperation(() -> store.init(null, null), "init()");
checkThrowsUnsupportedOperation(store::close, "close()");
}
private void checkThrowsUnsupportedOperation(final Runnable check, final String name) {
try {
check.run();
fail(name + " should throw exception");
} catch (final UnsupportedOperationException e) {
//ignore.
}
}
}
|
googleapis/google-cloud-java | 37,848 | java-vmwareengine/proto-google-cloud-vmwareengine-v1/src/main/java/com/google/cloud/vmwareengine/v1/Hcx.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/vmwareengine/v1/vmwareengine_resources.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vmwareengine.v1;
/**
*
*
* <pre>
* Details about a HCX Cloud Manager appliance.
* </pre>
*
* Protobuf type {@code google.cloud.vmwareengine.v1.Hcx}
*/
public final class Hcx extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vmwareengine.v1.Hcx)
HcxOrBuilder {
private static final long serialVersionUID = 0L;
// Use Hcx.newBuilder() to construct.
private Hcx(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Hcx() {
internalIp_ = "";
version_ = "";
state_ = 0;
fqdn_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Hcx();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vmwareengine.v1.VmwareengineResourcesProto
.internal_static_google_cloud_vmwareengine_v1_Hcx_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vmwareengine.v1.VmwareengineResourcesProto
.internal_static_google_cloud_vmwareengine_v1_Hcx_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vmwareengine.v1.Hcx.class,
com.google.cloud.vmwareengine.v1.Hcx.Builder.class);
}
/**
*
*
* <pre>
* State of the appliance
* </pre>
*
* Protobuf enum {@code google.cloud.vmwareengine.v1.Hcx.State}
*/
public enum State implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Unspecified appliance state. This is the default value.
* </pre>
*
* <code>STATE_UNSPECIFIED = 0;</code>
*/
STATE_UNSPECIFIED(0),
/**
*
*
* <pre>
* The appliance is operational and can be used.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
ACTIVE(1),
/**
*
*
* <pre>
* The appliance is being deployed.
* </pre>
*
* <code>CREATING = 2;</code>
*/
CREATING(2),
/**
*
*
* <pre>
* The appliance is being activated.
* </pre>
*
* <code>ACTIVATING = 3;</code>
*/
ACTIVATING(3),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Unspecified appliance state. This is the default value.
* </pre>
*
* <code>STATE_UNSPECIFIED = 0;</code>
*/
public static final int STATE_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* The appliance is operational and can be used.
* </pre>
*
* <code>ACTIVE = 1;</code>
*/
public static final int ACTIVE_VALUE = 1;
/**
*
*
* <pre>
* The appliance is being deployed.
* </pre>
*
* <code>CREATING = 2;</code>
*/
public static final int CREATING_VALUE = 2;
/**
*
*
* <pre>
* The appliance is being activated.
* </pre>
*
* <code>ACTIVATING = 3;</code>
*/
public static final int ACTIVATING_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static State valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static State forNumber(int value) {
switch (value) {
case 0:
return STATE_UNSPECIFIED;
case 1:
return ACTIVE;
case 2:
return CREATING;
case 3:
return ACTIVATING;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<State> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<State> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<State>() {
public State findValueByNumber(int number) {
return State.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.vmwareengine.v1.Hcx.getDescriptor().getEnumTypes().get(0);
}
private static final State[] VALUES = values();
public static State valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private State(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.vmwareengine.v1.Hcx.State)
}
public static final int INTERNAL_IP_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object internalIp_ = "";
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @return The internalIp.
*/
@java.lang.Override
public java.lang.String getInternalIp() {
java.lang.Object ref = internalIp_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
internalIp_ = s;
return s;
}
}
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @return The bytes for internalIp.
*/
@java.lang.Override
public com.google.protobuf.ByteString getInternalIpBytes() {
java.lang.Object ref = internalIp_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
internalIp_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object version_ = "";
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @return The version.
*/
@java.lang.Override
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @return The bytes for version.
*/
@java.lang.Override
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int STATE_FIELD_NUMBER = 5;
private int state_ = 0;
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for state.
*/
@java.lang.Override
public int getStateValue() {
return state_;
}
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The state.
*/
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx.State getState() {
com.google.cloud.vmwareengine.v1.Hcx.State result =
com.google.cloud.vmwareengine.v1.Hcx.State.forNumber(state_);
return result == null ? com.google.cloud.vmwareengine.v1.Hcx.State.UNRECOGNIZED : result;
}
public static final int FQDN_FIELD_NUMBER = 6;
@SuppressWarnings("serial")
private volatile java.lang.Object fqdn_ = "";
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @return The fqdn.
*/
@java.lang.Override
public java.lang.String getFqdn() {
java.lang.Object ref = fqdn_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
fqdn_ = s;
return s;
}
}
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @return The bytes for fqdn.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFqdnBytes() {
java.lang.Object ref = fqdn_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
fqdn_ = 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(internalIp_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, internalIp_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, version_);
}
if (state_ != com.google.cloud.vmwareengine.v1.Hcx.State.STATE_UNSPECIFIED.getNumber()) {
output.writeEnum(5, state_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(fqdn_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, fqdn_);
}
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(internalIp_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, internalIp_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, version_);
}
if (state_ != com.google.cloud.vmwareengine.v1.Hcx.State.STATE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(5, state_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(fqdn_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, fqdn_);
}
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.vmwareengine.v1.Hcx)) {
return super.equals(obj);
}
com.google.cloud.vmwareengine.v1.Hcx other = (com.google.cloud.vmwareengine.v1.Hcx) obj;
if (!getInternalIp().equals(other.getInternalIp())) return false;
if (!getVersion().equals(other.getVersion())) return false;
if (state_ != other.state_) return false;
if (!getFqdn().equals(other.getFqdn())) 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) + INTERNAL_IP_FIELD_NUMBER;
hash = (53 * hash) + getInternalIp().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
hash = (37 * hash) + STATE_FIELD_NUMBER;
hash = (53 * hash) + state_;
hash = (37 * hash) + FQDN_FIELD_NUMBER;
hash = (53 * hash) + getFqdn().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vmwareengine.v1.Hcx parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vmwareengine.v1.Hcx 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.vmwareengine.v1.Hcx parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vmwareengine.v1.Hcx 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.vmwareengine.v1.Hcx parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vmwareengine.v1.Hcx parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vmwareengine.v1.Hcx parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vmwareengine.v1.Hcx 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.vmwareengine.v1.Hcx parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vmwareengine.v1.Hcx 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.vmwareengine.v1.Hcx parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vmwareengine.v1.Hcx 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.vmwareengine.v1.Hcx prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Details about a HCX Cloud Manager appliance.
* </pre>
*
* Protobuf type {@code google.cloud.vmwareengine.v1.Hcx}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vmwareengine.v1.Hcx)
com.google.cloud.vmwareengine.v1.HcxOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vmwareengine.v1.VmwareengineResourcesProto
.internal_static_google_cloud_vmwareengine_v1_Hcx_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vmwareengine.v1.VmwareengineResourcesProto
.internal_static_google_cloud_vmwareengine_v1_Hcx_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vmwareengine.v1.Hcx.class,
com.google.cloud.vmwareengine.v1.Hcx.Builder.class);
}
// Construct using com.google.cloud.vmwareengine.v1.Hcx.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
internalIp_ = "";
version_ = "";
state_ = 0;
fqdn_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vmwareengine.v1.VmwareengineResourcesProto
.internal_static_google_cloud_vmwareengine_v1_Hcx_descriptor;
}
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx getDefaultInstanceForType() {
return com.google.cloud.vmwareengine.v1.Hcx.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx build() {
com.google.cloud.vmwareengine.v1.Hcx result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx buildPartial() {
com.google.cloud.vmwareengine.v1.Hcx result = new com.google.cloud.vmwareengine.v1.Hcx(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.vmwareengine.v1.Hcx result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.internalIp_ = internalIp_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.version_ = version_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.state_ = state_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.fqdn_ = fqdn_;
}
}
@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.vmwareengine.v1.Hcx) {
return mergeFrom((com.google.cloud.vmwareengine.v1.Hcx) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vmwareengine.v1.Hcx other) {
if (other == com.google.cloud.vmwareengine.v1.Hcx.getDefaultInstance()) return this;
if (!other.getInternalIp().isEmpty()) {
internalIp_ = other.internalIp_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.state_ != 0) {
setStateValue(other.getStateValue());
}
if (!other.getFqdn().isEmpty()) {
fqdn_ = other.fqdn_;
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 18:
{
internalIp_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 18
case 34:
{
version_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 34
case 40:
{
state_ = input.readEnum();
bitField0_ |= 0x00000004;
break;
} // case 40
case 50:
{
fqdn_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 50
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object internalIp_ = "";
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @return The internalIp.
*/
public java.lang.String getInternalIp() {
java.lang.Object ref = internalIp_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
internalIp_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @return The bytes for internalIp.
*/
public com.google.protobuf.ByteString getInternalIpBytes() {
java.lang.Object ref = internalIp_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
internalIp_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @param value The internalIp to set.
* @return This builder for chaining.
*/
public Builder setInternalIp(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
internalIp_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearInternalIp() {
internalIp_ = getDefaultInstance().getInternalIp();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Internal IP address of the appliance.
* </pre>
*
* <code>string internal_ip = 2;</code>
*
* @param value The bytes for internalIp to set.
* @return This builder for chaining.
*/
public Builder setInternalIpBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
internalIp_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object version_ = "";
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @return The version.
*/
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @return The bytes for version.
*/
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @param value The version to set.
* @return This builder for chaining.
*/
public Builder setVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearVersion() {
version_ = getDefaultInstance().getVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Version of the appliance.
* </pre>
*
* <code>string version = 4;</code>
*
* @param value The bytes for version to set.
* @return This builder for chaining.
*/
public Builder setVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int state_ = 0;
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for state.
*/
@java.lang.Override
public int getStateValue() {
return state_;
}
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @param value The enum numeric value on the wire for state to set.
* @return This builder for chaining.
*/
public Builder setStateValue(int value) {
state_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The state.
*/
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx.State getState() {
com.google.cloud.vmwareengine.v1.Hcx.State result =
com.google.cloud.vmwareengine.v1.Hcx.State.forNumber(state_);
return result == null ? com.google.cloud.vmwareengine.v1.Hcx.State.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @param value The state to set.
* @return This builder for chaining.
*/
public Builder setState(com.google.cloud.vmwareengine.v1.Hcx.State value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
state_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The state of the appliance.
* </pre>
*
* <code>
* .google.cloud.vmwareengine.v1.Hcx.State state = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearState() {
bitField0_ = (bitField0_ & ~0x00000004);
state_ = 0;
onChanged();
return this;
}
private java.lang.Object fqdn_ = "";
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @return The fqdn.
*/
public java.lang.String getFqdn() {
java.lang.Object ref = fqdn_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
fqdn_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @return The bytes for fqdn.
*/
public com.google.protobuf.ByteString getFqdnBytes() {
java.lang.Object ref = fqdn_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
fqdn_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @param value The fqdn to set.
* @return This builder for chaining.
*/
public Builder setFqdn(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
fqdn_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearFqdn() {
fqdn_ = getDefaultInstance().getFqdn();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Fully qualified domain name of the appliance.
* </pre>
*
* <code>string fqdn = 6;</code>
*
* @param value The bytes for fqdn to set.
* @return This builder for chaining.
*/
public Builder setFqdnBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
fqdn_ = 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.vmwareengine.v1.Hcx)
}
// @@protoc_insertion_point(class_scope:google.cloud.vmwareengine.v1.Hcx)
private static final com.google.cloud.vmwareengine.v1.Hcx DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vmwareengine.v1.Hcx();
}
public static com.google.cloud.vmwareengine.v1.Hcx getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Hcx> PARSER =
new com.google.protobuf.AbstractParser<Hcx>() {
@java.lang.Override
public Hcx 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<Hcx> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Hcx> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vmwareengine.v1.Hcx getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,019 | java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateServiceBindingRequest.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/service_binding.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.networkservices.v1;
/**
*
*
* <pre>
* Request used by the ServiceBinding method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.CreateServiceBindingRequest}
*/
public final class CreateServiceBindingRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateServiceBindingRequest)
CreateServiceBindingRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateServiceBindingRequest.newBuilder() to construct.
private CreateServiceBindingRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateServiceBindingRequest() {
parent_ = "";
serviceBindingId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateServiceBindingRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.ServiceBindingProto
.internal_static_google_cloud_networkservices_v1_CreateServiceBindingRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.ServiceBindingProto
.internal_static_google_cloud_networkservices_v1_CreateServiceBindingRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.CreateServiceBindingRequest.class,
com.google.cloud.networkservices.v1.CreateServiceBindingRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICE_BINDING_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object serviceBindingId_ = "";
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The serviceBindingId.
*/
@java.lang.Override
public java.lang.String getServiceBindingId() {
java.lang.Object ref = serviceBindingId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceBindingId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for serviceBindingId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceBindingIdBytes() {
java.lang.Object ref = serviceBindingId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceBindingId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICE_BINDING_FIELD_NUMBER = 3;
private com.google.cloud.networkservices.v1.ServiceBinding serviceBinding_;
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the serviceBinding field is set.
*/
@java.lang.Override
public boolean hasServiceBinding() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The serviceBinding.
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.ServiceBinding getServiceBinding() {
return serviceBinding_ == null
? com.google.cloud.networkservices.v1.ServiceBinding.getDefaultInstance()
: serviceBinding_;
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.ServiceBindingOrBuilder getServiceBindingOrBuilder() {
return serviceBinding_ == null
? com.google.cloud.networkservices.v1.ServiceBinding.getDefaultInstance()
: serviceBinding_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceBindingId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, serviceBindingId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getServiceBinding());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceBindingId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, serviceBindingId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getServiceBinding());
}
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.CreateServiceBindingRequest)) {
return super.equals(obj);
}
com.google.cloud.networkservices.v1.CreateServiceBindingRequest other =
(com.google.cloud.networkservices.v1.CreateServiceBindingRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getServiceBindingId().equals(other.getServiceBindingId())) return false;
if (hasServiceBinding() != other.hasServiceBinding()) return false;
if (hasServiceBinding()) {
if (!getServiceBinding().equals(other.getServiceBinding())) 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) + SERVICE_BINDING_ID_FIELD_NUMBER;
hash = (53 * hash) + getServiceBindingId().hashCode();
if (hasServiceBinding()) {
hash = (37 * hash) + SERVICE_BINDING_FIELD_NUMBER;
hash = (53 * hash) + getServiceBinding().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest 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.CreateServiceBindingRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest 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.CreateServiceBindingRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest 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.CreateServiceBindingRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest 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.CreateServiceBindingRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest 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.CreateServiceBindingRequest 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.CreateServiceBindingRequest 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.CreateServiceBindingRequest 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 ServiceBinding method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.CreateServiceBindingRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateServiceBindingRequest)
com.google.cloud.networkservices.v1.CreateServiceBindingRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.ServiceBindingProto
.internal_static_google_cloud_networkservices_v1_CreateServiceBindingRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.ServiceBindingProto
.internal_static_google_cloud_networkservices_v1_CreateServiceBindingRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.CreateServiceBindingRequest.class,
com.google.cloud.networkservices.v1.CreateServiceBindingRequest.Builder.class);
}
// Construct using com.google.cloud.networkservices.v1.CreateServiceBindingRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getServiceBindingFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
serviceBindingId_ = "";
serviceBinding_ = null;
if (serviceBindingBuilder_ != null) {
serviceBindingBuilder_.dispose();
serviceBindingBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.networkservices.v1.ServiceBindingProto
.internal_static_google_cloud_networkservices_v1_CreateServiceBindingRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateServiceBindingRequest
getDefaultInstanceForType() {
return com.google.cloud.networkservices.v1.CreateServiceBindingRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateServiceBindingRequest build() {
com.google.cloud.networkservices.v1.CreateServiceBindingRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateServiceBindingRequest buildPartial() {
com.google.cloud.networkservices.v1.CreateServiceBindingRequest result =
new com.google.cloud.networkservices.v1.CreateServiceBindingRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.networkservices.v1.CreateServiceBindingRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.serviceBindingId_ = serviceBindingId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.serviceBinding_ =
serviceBindingBuilder_ == null ? serviceBinding_ : serviceBindingBuilder_.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.networkservices.v1.CreateServiceBindingRequest) {
return mergeFrom((com.google.cloud.networkservices.v1.CreateServiceBindingRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.networkservices.v1.CreateServiceBindingRequest other) {
if (other
== com.google.cloud.networkservices.v1.CreateServiceBindingRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getServiceBindingId().isEmpty()) {
serviceBindingId_ = other.serviceBindingId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasServiceBinding()) {
mergeServiceBinding(other.getServiceBinding());
}
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:
{
serviceBindingId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getServiceBindingFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource of the ServiceBinding. Must be in the
* format `projects/*/locations/*`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object serviceBindingId_ = "";
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The serviceBindingId.
*/
public java.lang.String getServiceBindingId() {
java.lang.Object ref = serviceBindingId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceBindingId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for serviceBindingId.
*/
public com.google.protobuf.ByteString getServiceBindingIdBytes() {
java.lang.Object ref = serviceBindingId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceBindingId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The serviceBindingId to set.
* @return This builder for chaining.
*/
public Builder setServiceBindingId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceBindingId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceBindingId() {
serviceBindingId_ = getDefaultInstance().getServiceBindingId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Short name of the ServiceBinding resource to be created.
* </pre>
*
* <code>string service_binding_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for serviceBindingId to set.
* @return This builder for chaining.
*/
public Builder setServiceBindingIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceBindingId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.networkservices.v1.ServiceBinding serviceBinding_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.ServiceBinding,
com.google.cloud.networkservices.v1.ServiceBinding.Builder,
com.google.cloud.networkservices.v1.ServiceBindingOrBuilder>
serviceBindingBuilder_;
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the serviceBinding field is set.
*/
public boolean hasServiceBinding() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The serviceBinding.
*/
public com.google.cloud.networkservices.v1.ServiceBinding getServiceBinding() {
if (serviceBindingBuilder_ == null) {
return serviceBinding_ == null
? com.google.cloud.networkservices.v1.ServiceBinding.getDefaultInstance()
: serviceBinding_;
} else {
return serviceBindingBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServiceBinding(com.google.cloud.networkservices.v1.ServiceBinding value) {
if (serviceBindingBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
serviceBinding_ = value;
} else {
serviceBindingBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServiceBinding(
com.google.cloud.networkservices.v1.ServiceBinding.Builder builderForValue) {
if (serviceBindingBuilder_ == null) {
serviceBinding_ = builderForValue.build();
} else {
serviceBindingBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeServiceBinding(com.google.cloud.networkservices.v1.ServiceBinding value) {
if (serviceBindingBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& serviceBinding_ != null
&& serviceBinding_
!= com.google.cloud.networkservices.v1.ServiceBinding.getDefaultInstance()) {
getServiceBindingBuilder().mergeFrom(value);
} else {
serviceBinding_ = value;
}
} else {
serviceBindingBuilder_.mergeFrom(value);
}
if (serviceBinding_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearServiceBinding() {
bitField0_ = (bitField0_ & ~0x00000004);
serviceBinding_ = null;
if (serviceBindingBuilder_ != null) {
serviceBindingBuilder_.dispose();
serviceBindingBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.ServiceBinding.Builder getServiceBindingBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getServiceBindingFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.ServiceBindingOrBuilder
getServiceBindingOrBuilder() {
if (serviceBindingBuilder_ != null) {
return serviceBindingBuilder_.getMessageOrBuilder();
} else {
return serviceBinding_ == null
? com.google.cloud.networkservices.v1.ServiceBinding.getDefaultInstance()
: serviceBinding_;
}
}
/**
*
*
* <pre>
* Required. ServiceBinding resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.ServiceBinding service_binding = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.ServiceBinding,
com.google.cloud.networkservices.v1.ServiceBinding.Builder,
com.google.cloud.networkservices.v1.ServiceBindingOrBuilder>
getServiceBindingFieldBuilder() {
if (serviceBindingBuilder_ == null) {
serviceBindingBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.ServiceBinding,
com.google.cloud.networkservices.v1.ServiceBinding.Builder,
com.google.cloud.networkservices.v1.ServiceBindingOrBuilder>(
getServiceBinding(), getParentForChildren(), isClean());
serviceBinding_ = null;
}
return serviceBindingBuilder_;
}
@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.CreateServiceBindingRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateServiceBindingRequest)
private static final com.google.cloud.networkservices.v1.CreateServiceBindingRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateServiceBindingRequest();
}
public static com.google.cloud.networkservices.v1.CreateServiceBindingRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateServiceBindingRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateServiceBindingRequest>() {
@java.lang.Override
public CreateServiceBindingRequest 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<CreateServiceBindingRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateServiceBindingRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateServiceBindingRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 38,206 | jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/X509TrustManagerImpl/PKIXExtendedTM.java | /*
* Copyright (c) 2010, 2011, 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.
*
* 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.
*/
/*
* @test
* @bug 6916074
* @summary Add support for TLS 1.2
* @run main/othervm PKIXExtendedTM
*
* SunJSSE does not support dynamic system properties, no way to re-use
* system properties in samevm/agentvm mode.
*/
import java.net.*;
import java.util.*;
import java.io.*;
import javax.net.ssl.*;
import java.security.KeyStore;
import java.security.KeyFactory;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.*;
import java.security.interfaces.*;
import java.math.BigInteger;
/*
* Certificates and key used in the test.
*
* TLS server certificate:
* server private key:
* -----BEGIN RSA PRIVATE KEY-----
* Proc-Type: 4,ENCRYPTED
* DEK-Info: DES-EDE3-CBC,D9AE407F6D0E389A
*
* WPrA7TFol/cQCcp9oHnXWNpYlvRbbIcQj0m+RKT2Iuzfus+DHt3Zadf8nJpKfX2e
* h2rnhlzCN9M7djRDooZKDOPCsdBn51Au7HlZF3S3Opgo7D8XFM1a8t1Je4ke14oI
* nw6QKYsBblRziPnP2PZ0zvX24nOv7bbY8beynlJHGs00VWSFdoH2DS0aE1p6D+3n
* ptJuJ75dVfZFK4X7162APlNXevX8D6PEQpSiRw1rjjGGcnvQ4HdWk3BxDVDcCNJb
* Y1aGNRxsjTDvPi3R9Qx2M+W03QzEPx4SR3ZHVskeSJHaetM0TM/w/45Paq4GokXP
* ZeTnbEx1xmjkA7h+t4doLL4watx5F6yLsJzu8xB3lt/1EtmkYtLz1t7X4BetPAXz
* zS69X/VwhKfsOI3qXBWuL2oHPyhDmT1gcaUQwEPSV6ogHEEQEDXdiUS8heNK13KF
* TCQYFkETvV2BLxUhV1hypPzRQ6tUpJiAbD5KmoK2lD9slshG2QtvKQq0/bgkDY5J
* LhDHV2dtcZ3kDPkkZXpbcJQvoeH3d09C5sIsuTFo2zgNR6oETHUc5TzP6FY2YYRa
* QcK5HcmtsRRiXFm01ac+aMejJUIujjFt84SiKWT/73vC8AmY4tYcJBLjCg4XIxSH
* fdDFLL1YZENNO5ivlp8mdiHqcawx+36L7DrEZQ8RZt6cqST5t/+XTdM74s6k81GT
* pNsa82P2K2zmIUZ/DL2mKjW1vfRByw1NQFEBkN3vdyZxYfM/JyUzX4hbjXBEkh9Q
* QYrcwLKLjis2QzSvK04B3bvRzRb+4ocWiso8ZPAXAIxZFBWDpTMM2A==
* -----END RSA PRIVATE KEY-----
*
* -----BEGIN RSA PRIVATE KEY-----
* MIICXAIBAAKBgQClrFscN6LdmYktsnm4j9VIpecchBeNaZzGrG358h0fORna03Ie
* buxEzHCk3LoAMPagTz1UemFqzFfQCn+VKBg/mtmU8hvIJIh+/p0PPftXUwizIDPU
* PxdHFNHN6gjYDnVOr77M0uyvqXpJ38LZrLgkQJCmA1Yq0DAFQCxPq9l0iQIDAQAB
* AoGAbqcbg1E1mkR99uOJoNeQYKFOJyGiiXTMnXV1TseC4+PDfQBU7Dax35GcesBi
* CtapIpFKKS5D+ozY6b7ZT8ojxuQ/uHLPAvz0WDR3ds4iRF8tyu71Q1ZHcQsJa17y
* yO7UbkSSKn/Mp9Rb+/dKqftUGNXVFLqgHBOzN2s3We3bbbECQQDYBPKOg3hkaGHo
* OhpHKqtQ6EVkldihG/3i4WejRonelXN+HRh1KrB2HBx0M8D/qAzP1i3rNSlSHer4
* 59YRTJnHAkEAxFX/sVYSn07BHv9Zhn6XXct/Cj43z/tKNbzlNbcxqQwQerw3IH51
* 8UH2YOA+GD3lXbKp+MytoFLWv8zg4YT/LwJAfqan75Z1R6lLffRS49bIiq8jwE16
* rTrUJ+kv8jKxMqc9B3vXkxpsS1M/+4E8bqgAmvpgAb8xcsvHsBd9ErdukQJBAKs2
* j67W75BrPjBI34pQ1LEfp56IGWXOrq1kF8IbCjxv3+MYRT6Z6UJFkpRymNPNDjsC
* dgUYgITiGJHUGXuw3lMCQHEHqo9ZtXz92yFT+VhsNc29B8m/sqUJdtCcMd/jGpAF
* u6GHufjqIZBpQsk63wbwESAPZZ+kk1O1kS5GIRLX608=
* -----END RSA PRIVATE KEY-----
*
* Private-Key: (1024 bit)
* modulus:
* 00:a5:ac:5b:1c:37:a2:dd:99:89:2d:b2:79:b8:8f:
* d5:48:a5:e7:1c:84:17:8d:69:9c:c6:ac:6d:f9:f2:
* 1d:1f:39:19:da:d3:72:1e:6e:ec:44:cc:70:a4:dc:
* ba:00:30:f6:a0:4f:3d:54:7a:61:6a:cc:57:d0:0a:
* 7f:95:28:18:3f:9a:d9:94:f2:1b:c8:24:88:7e:fe:
* 9d:0f:3d:fb:57:53:08:b3:20:33:d4:3f:17:47:14:
* d1:cd:ea:08:d8:0e:75:4e:af:be:cc:d2:ec:af:a9:
* 7a:49:df:c2:d9:ac:b8:24:40:90:a6:03:56:2a:d0:
* 30:05:40:2c:4f:ab:d9:74:89
* publicExponent: 65537 (0x10001)
* privateExponent:
* 6e:a7:1b:83:51:35:9a:44:7d:f6:e3:89:a0:d7:90:
* 60:a1:4e:27:21:a2:89:74:cc:9d:75:75:4e:c7:82:
* e3:e3:c3:7d:00:54:ec:36:b1:df:91:9c:7a:c0:62:
* 0a:d6:a9:22:91:4a:29:2e:43:fa:8c:d8:e9:be:d9:
* 4f:ca:23:c6:e4:3f:b8:72:cf:02:fc:f4:58:34:77:
* 76:ce:22:44:5f:2d:ca:ee:f5:43:56:47:71:0b:09:
* 6b:5e:f2:c8:ee:d4:6e:44:92:2a:7f:cc:a7:d4:5b:
* fb:f7:4a:a9:fb:54:18:d5:d5:14:ba:a0:1c:13:b3:
* 37:6b:37:59:ed:db:6d:b1
* prime1:
* 00:d8:04:f2:8e:83:78:64:68:61:e8:3a:1a:47:2a:
* ab:50:e8:45:64:95:d8:a1:1b:fd:e2:e1:67:a3:46:
* 89:de:95:73:7e:1d:18:75:2a:b0:76:1c:1c:74:33:
* c0:ff:a8:0c:cf:d6:2d:eb:35:29:52:1d:ea:f8:e7:
* d6:11:4c:99:c7
* prime2:
* 00:c4:55:ff:b1:56:12:9f:4e:c1:1e:ff:59:86:7e:
* 97:5d:cb:7f:0a:3e:37:cf:fb:4a:35:bc:e5:35:b7:
* 31:a9:0c:10:7a:bc:37:20:7e:75:f1:41:f6:60:e0:
* 3e:18:3d:e5:5d:b2:a9:f8:cc:ad:a0:52:d6:bf:cc:
* e0:e1:84:ff:2f
* exponent1:
* 7e:a6:a7:ef:96:75:47:a9:4b:7d:f4:52:e3:d6:c8:
* 8a:af:23:c0:4d:7a:ad:3a:d4:27:e9:2f:f2:32:b1:
* 32:a7:3d:07:7b:d7:93:1a:6c:4b:53:3f:fb:81:3c:
* 6e:a8:00:9a:fa:60:01:bf:31:72:cb:c7:b0:17:7d:
* 12:b7:6e:91
* exponent2:
* 00:ab:36:8f:ae:d6:ef:90:6b:3e:30:48:df:8a:50:
* d4:b1:1f:a7:9e:88:19:65:ce:ae:ad:64:17:c2:1b:
* 0a:3c:6f:df:e3:18:45:3e:99:e9:42:45:92:94:72:
* 98:d3:cd:0e:3b:02:76:05:18:80:84:e2:18:91:d4:
* 19:7b:b0:de:53
* coefficient:
* 71:07:aa:8f:59:b5:7c:fd:db:21:53:f9:58:6c:35:
* cd:bd:07:c9:bf:b2:a5:09:76:d0:9c:31:df:e3:1a:
* 90:05:bb:a1:87:b9:f8:ea:21:90:69:42:c9:3a:df:
* 06:f0:11:20:0f:65:9f:a4:93:53:b5:91:2e:46:21:
* 12:d7:eb:4f
*
*
* server certificate:
* Data:
* Version: 3 (0x2)
* Serial Number: 8 (0x8)
* Signature Algorithm: md5WithRSAEncryption
* Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org
* Validity
* Not Before: Dec 8 03:43:04 2008 GMT
* Not After : Aug 25 03:43:04 2028 GMT
* Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org, OU=SSL-Server, CN=localhost
* Subject Public Key Info:
* Public Key Algorithm: rsaEncryption
* RSA Public Key: (1024 bit)
* Modulus (1024 bit):
* 00:a5:ac:5b:1c:37:a2:dd:99:89:2d:b2:79:b8:8f:
* d5:48:a5:e7:1c:84:17:8d:69:9c:c6:ac:6d:f9:f2:
* 1d:1f:39:19:da:d3:72:1e:6e:ec:44:cc:70:a4:dc:
* ba:00:30:f6:a0:4f:3d:54:7a:61:6a:cc:57:d0:0a:
* 7f:95:28:18:3f:9a:d9:94:f2:1b:c8:24:88:7e:fe:
* 9d:0f:3d:fb:57:53:08:b3:20:33:d4:3f:17:47:14:
* d1:cd:ea:08:d8:0e:75:4e:af:be:cc:d2:ec:af:a9:
* 7a:49:df:c2:d9:ac:b8:24:40:90:a6:03:56:2a:d0:
* 30:05:40:2c:4f:ab:d9:74:89
* Exponent: 65537 (0x10001)
* X509v3 extensions:
* X509v3 Basic Constraints:
* CA:FALSE
* X509v3 Key Usage:
* Digital Signature, Non Repudiation, Key Encipherment
* X509v3 Subject Key Identifier:
* ED:6E:DB:F4:B5:56:C8:FB:1A:06:61:3F:0F:08:BB:A6:04:D8:16:54
* X509v3 Authority Key Identifier:
* keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
*
* X509v3 Subject Alternative Name: critical
* DNS:localhost
* Signature Algorithm: md5WithRSAEncryption0
*
* -----BEGIN CERTIFICATE-----
* MIICpDCCAg2gAwIBAgIBCDANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET
* MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK
* EwhTb21lLU9yZzAeFw0wODEyMDgwMzQzMDRaFw0yODA4MjUwMzQzMDRaMHIxCzAJ
* BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp
* dHkxETAPBgNVBAoTCFNvbWUtT3JnMRMwEQYDVQQLEwpTU0wtU2VydmVyMRIwEAYD
* VQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKWsWxw3
* ot2ZiS2yebiP1Uil5xyEF41pnMasbfnyHR85GdrTch5u7ETMcKTcugAw9qBPPVR6
* YWrMV9AKf5UoGD+a2ZTyG8gkiH7+nQ89+1dTCLMgM9Q/F0cU0c3qCNgOdU6vvszS
* 7K+peknfwtmsuCRAkKYDVirQMAVALE+r2XSJAgMBAAGjczBxMAkGA1UdEwQCMAAw
* CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTtbtv0tVbI+xoGYT8PCLumBNgWVDAfBgNV
* HSMEGDAWgBT6uVG/TOfZhpgz+efLHvEzSfeoFDAXBgNVHREBAf8EDTALgglsb2Nh
* bGhvc3QwDQYJKoZIhvcNAQEEBQADgYEAoqVTciHtcvsUj+YaTct8tUh3aTCsKsac
* PHhfQ+ObjiXSgxsKYTX7ym/wk/wvlbUcbqLKxsu7qrcJitH+H9heV1hEHEu65Uoi
* nRugFruyOrwvAylV8Cm2af7ddilmYJ+sdJA6N2M3xJRxR0G2LFHEXDNEjYReyexn
* JqCpf5uZGOo=
* -----END CERTIFICATE-----
*
*
* TLS client certificate:
* client private key:
* ----BEGIN RSA PRIVATE KEY-----
* Proc-Type: 4,ENCRYPTED
* DEK-Info: DES-EDE3-CBC,FA2A435CD35A9390
*
* Z+Y2uaETbsUWIyJUyVu1UV2G4rgFYJyACZT6Tp1KjRtxflSh2kXkJ9MpuXMXA0V4
* Yy3fDzPqCL9NJmQAYRlAx/W/+j4F5EyMWDIx8fUxzONRZyoiwF7jLm+KscAfv6Pf
* q7ItWOdj3z7IYrwlB8YIGd3F2cDKT3S+lYRk7rKb/qT7itbuHnY4Ardh3yl+MZak
* jBp+ELUlRsUqSr1V0LoM+0rCCykarpyfhpxEcqsrl0v9Cyi5uhU50/oKv5zql3SH
* l2ImgDjp3batAs8+Bd4NF2aqi0a7Hy44JUHxRm4caZryU/i/D9N1MbuM6882HLat
* 5N0G+NaIUfywa8mjwq2D5aiit18HqKA6XeRRYeJ5Dvu9DCO4GeFSwcUFIBMI0L46
* 7s114+oDodg57pMgITi+04vmUxvqlN9aiyd7f5Fgd7PeHGeOdbMz1NaJLJaPI9++
* NakK8eK9iwT/Gdq0Uap5/CHW7vCT5PO+h3HY0STH0lWStXhdWnFO04zTdywsbSp+
* DLpHeFT66shfeUlxR0PsCbG9vPRt/QmGLeYQZITppWo/ylSq4j+pRIuXvuWHdBRN
* rTZ8QF4Y7AxQUXVz1j1++s6ZMHTzaK2i9HrhmDs1MbJl+QwWre3Xpv3LvTVz3k5U
* wX8kuY1m3STt71QCaRWENq5sRaMImLxZbxc/ivFl9RAzUqo4NCxLod/QgA4iLqtO
* ztnlpzwlC/F8HbQ1oqYWwnZAPhzU/cULtstl+Yrws2c2atO323LbPXZqbASySgig
* sNpFXQMObdfP6LN23bY+1SvtK7V4NUTNhpdIc6INQAQ=
* -----END RSA PRIVATE KEY-----
*
* -----BEGIN RSA PRIVATE KEY-----
* MIICWwIBAAKBgQC78EA2rCZUTvSjWgAvaSFvuXo6k+yi9uGOx2PYLxIwmS6w8o/4
* Jy0keCiE9wG/jUR53TvSVfPOPLJbIX3v/TNKsaP/xsibuQ98QTWX+ds6BWAFFa9Z
* F5KjEK0WHOQHU6+odqJWKpLT+SjgeM9eH0irXBnd4WdDunWN9YKsQ5JEGwIDAQAB
* AoGAEbdqNj0wN85hnWyEi/ObJU8UyKTdL9eaF72QGfcF/fLSxfd3vurihIeXOkGW
* tpn4lIxYcVGM9CognhqgJpl11jFTQzn1KqZ+NEJRKkCHA4hDabKJbSC9fXHvRwrf
* BsFpZqgiNxp3HseUTiwnaUVeyPgMt/jAj5nB5Sib+UyUxrECQQDnNQBiF2aifEg6
* zbJOOC7he5CHAdkFxSxWVFVHL6EfXfqdLVkUohMbgZv+XxyIeU2biOExSg49Kds3
* FOKgTau1AkEA0Bd1haj6QuCo8I0AXm2WO+MMTZMTvtHD/bGjKNM+fT4I8rKYnQRX
* 1acHdqS9Xx2rNJqZgkMmpESIdPR2fc4yjwJALFeM6EMmqvj8/VIf5UJ/Mz14fXwM
* PEARfckUxd9LnnFutCBTWlKvKXJVEZb6KO5ixPaegc57Jp3Vbh3yTN44lQJADD/1
* SSMDaIB1MYP7a5Oj7m6VQNPRq8AJe5vDcRnOae0G9dKRrVyeFxO4GsHj6/+BHp2j
* P8nYMn9eURQ7DXjf/QJAAQzMlWnKGSO8pyTDtnQx3hRMoUkOEhmNq4bQhLkYqtnY
* FcqpUQ2qMjW+NiNWk5HnTrMS3L9EdJobMUzaNZLy4w==
* -----END RSA PRIVATE KEY-----
*
* Private-Key: (1024 bit)
* modulus:
* 00:bb:f0:40:36:ac:26:54:4e:f4:a3:5a:00:2f:69:
* 21:6f:b9:7a:3a:93:ec:a2:f6:e1:8e:c7:63:d8:2f:
* 12:30:99:2e:b0:f2:8f:f8:27:2d:24:78:28:84:f7:
* 01:bf:8d:44:79:dd:3b:d2:55:f3:ce:3c:b2:5b:21:
* 7d:ef:fd:33:4a:b1:a3:ff:c6:c8:9b:b9:0f:7c:41:
* 35:97:f9:db:3a:05:60:05:15:af:59:17:92:a3:10:
* ad:16:1c:e4:07:53:af:a8:76:a2:56:2a:92:d3:f9:
* 28:e0:78:cf:5e:1f:48:ab:5c:19:dd:e1:67:43:ba:
* 75:8d:f5:82:ac:43:92:44:1b
* publicExponent: 65537 (0x10001)
* privateExponent:
* 11:b7:6a:36:3d:30:37:ce:61:9d:6c:84:8b:f3:9b:
* 25:4f:14:c8:a4:dd:2f:d7:9a:17:bd:90:19:f7:05:
* fd:f2:d2:c5:f7:77:be:ea:e2:84:87:97:3a:41:96:
* b6:99:f8:94:8c:58:71:51:8c:f4:2a:20:9e:1a:a0:
* 26:99:75:d6:31:53:43:39:f5:2a:a6:7e:34:42:51:
* 2a:40:87:03:88:43:69:b2:89:6d:20:bd:7d:71:ef:
* 47:0a:df:06:c1:69:66:a8:22:37:1a:77:1e:c7:94:
* 4e:2c:27:69:45:5e:c8:f8:0c:b7:f8:c0:8f:99:c1:
* e5:28:9b:f9:4c:94:c6:b1
* prime1:
* 00:e7:35:00:62:17:66:a2:7c:48:3a:cd:b2:4e:38:
* 2e:e1:7b:90:87:01:d9:05:c5:2c:56:54:55:47:2f:
* a1:1f:5d:fa:9d:2d:59:14:a2:13:1b:81:9b:fe:5f:
* 1c:88:79:4d:9b:88:e1:31:4a:0e:3d:29:db:37:14:
* e2:a0:4d:ab:b5
* prime2:
* 00:d0:17:75:85:a8:fa:42:e0:a8:f0:8d:00:5e:6d:
* 96:3b:e3:0c:4d:93:13:be:d1:c3:fd:b1:a3:28:d3:
* 3e:7d:3e:08:f2:b2:98:9d:04:57:d5:a7:07:76:a4:
* bd:5f:1d:ab:34:9a:99:82:43:26:a4:44:88:74:f4:
* 76:7d:ce:32:8f
* exponent1:
* 2c:57:8c:e8:43:26:aa:f8:fc:fd:52:1f:e5:42:7f:
* 33:3d:78:7d:7c:0c:3c:40:11:7d:c9:14:c5:df:4b:
* 9e:71:6e:b4:20:53:5a:52:af:29:72:55:11:96:fa:
* 28:ee:62:c4:f6:9e:81:ce:7b:26:9d:d5:6e:1d:f2:
* 4c:de:38:95
* exponent2:
* 0c:3f:f5:49:23:03:68:80:75:31:83:fb:6b:93:a3:
* ee:6e:95:40:d3:d1:ab:c0:09:7b:9b:c3:71:19:ce:
* 69:ed:06:f5:d2:91:ad:5c:9e:17:13:b8:1a:c1:e3:
* eb:ff:81:1e:9d:a3:3f:c9:d8:32:7f:5e:51:14:3b:
* 0d:78:df:fd
* coefficient:
* 01:0c:cc:95:69:ca:19:23:bc:a7:24:c3:b6:74:31:
* de:14:4c:a1:49:0e:12:19:8d:ab:86:d0:84:b9:18:
* aa:d9:d8:15:ca:a9:51:0d:aa:32:35:be:36:23:56:
* 93:91:e7:4e:b3:12:dc:bf:44:74:9a:1b:31:4c:da:
* 35:92:f2:e3
*
* client certificate:
* Data:
* Version: 3 (0x2)
* Serial Number: 9 (0x9)
* Signature Algorithm: md5WithRSAEncryption
* Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org
* Validity
* Not Before: Dec 8 03:43:24 2008 GMT
* Not After : Aug 25 03:43:24 2028 GMT
* Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org, OU=SSL-Client, CN=localhost
* Subject Public Key Info:
* Public Key Algorithm: rsaEncryption
* RSA Public Key: (1024 bit)
* Modulus (1024 bit):
* 00:bb:f0:40:36:ac:26:54:4e:f4:a3:5a:00:2f:69:
* 21:6f:b9:7a:3a:93:ec:a2:f6:e1:8e:c7:63:d8:2f:
* 12:30:99:2e:b0:f2:8f:f8:27:2d:24:78:28:84:f7:
* 01:bf:8d:44:79:dd:3b:d2:55:f3:ce:3c:b2:5b:21:
* 7d:ef:fd:33:4a:b1:a3:ff:c6:c8:9b:b9:0f:7c:41:
* 35:97:f9:db:3a:05:60:05:15:af:59:17:92:a3:10:
* ad:16:1c:e4:07:53:af:a8:76:a2:56:2a:92:d3:f9:
* 28:e0:78:cf:5e:1f:48:ab:5c:19:dd:e1:67:43:ba:
* 75:8d:f5:82:ac:43:92:44:1b
* Exponent: 65537 (0x10001)
* X509v3 extensions:
* X509v3 Basic Constraints:
* CA:FALSE
* X509v3 Key Usage:
* Digital Signature, Non Repudiation, Key Encipherment
* X509v3 Subject Key Identifier:
* CD:BB:C8:85:AA:91:BD:FD:1D:BE:CD:67:7C:FF:B3:E9:4C:A8:22:E6
* X509v3 Authority Key Identifier:
* keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
*
* X509v3 Subject Alternative Name: critical
* DNS:localhost
* Signature Algorithm: md5WithRSAEncryption
*
* -----BEGIN CERTIFICATE-----
* MIICpDCCAg2gAwIBAgIBCTANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET
* MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK
* EwhTb21lLU9yZzAeFw0wODEyMDgwMzQzMjRaFw0yODA4MjUwMzQzMjRaMHIxCzAJ
* BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp
* dHkxETAPBgNVBAoTCFNvbWUtT3JnMRMwEQYDVQQLEwpTU0wtQ2xpZW50MRIwEAYD
* VQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALvwQDas
* JlRO9KNaAC9pIW+5ejqT7KL24Y7HY9gvEjCZLrDyj/gnLSR4KIT3Ab+NRHndO9JV
* 8848slshfe/9M0qxo//GyJu5D3xBNZf52zoFYAUVr1kXkqMQrRYc5AdTr6h2olYq
* ktP5KOB4z14fSKtcGd3hZ0O6dY31gqxDkkQbAgMBAAGjczBxMAkGA1UdEwQCMAAw
* CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTNu8iFqpG9/R2+zWd8/7PpTKgi5jAfBgNV
* HSMEGDAWgBT6uVG/TOfZhpgz+efLHvEzSfeoFDAXBgNVHREBAf8EDTALgglsb2Nh
* bGhvc3QwDQYJKoZIhvcNAQEEBQADgYEAm25gJyqW1JznQ1EyOtTGswBVwfgBOf+F
* HJuBTcflYQLbTD/AETPQJGvZU9tdhuLtbG3OPhR7vSY8zeAbfM3dbH7QFr3r47Gj
* XEH7qM/MX+Z3ifVaC4MeJmrYQkYFSuKeyyKpdRVX4w4nnFHF6OsNASsYrMW6LpxN
* cl/epUcHL7E=
* -----END CERTIFICATE-----
*
*
*
* Trusted CA certificate:
* Certificate:
* Data:
* Version: 3 (0x2)
* Serial Number: 0 (0x0)
* Signature Algorithm: md5WithRSAEncryption
* Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org
* Validity
* Not Before: Dec 8 02:43:36 2008 GMT
* Not After : Aug 25 02:43:36 2028 GMT
* Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org
* Subject Public Key Info:
* Public Key Algorithm: rsaEncryption
* RSA Public Key: (1024 bit)
* Modulus (1024 bit):
* 00:cb:c4:38:20:07:be:88:a7:93:b0:a1:43:51:2d:
* d7:8e:85:af:54:dd:ad:a2:7b:23:5b:cf:99:13:53:
* 99:45:7d:ee:6d:ba:2d:bf:e3:ad:6e:3d:9f:1a:f9:
* 03:97:e0:17:55:ae:11:26:57:de:01:29:8e:05:3f:
* 21:f7:e7:36:e8:2e:37:d7:48:ac:53:d6:60:0e:c7:
* 50:6d:f6:c5:85:f7:8b:a6:c5:91:35:72:3c:94:ee:
* f1:17:f0:71:e3:ec:1b:ce:ca:4e:40:42:b0:6d:ee:
* 6a:0e:d6:e5:ad:3c:0f:c9:ba:82:4f:78:f8:89:97:
* 89:2a:95:12:4c:d8:09:2a:e9
* Exponent: 65537 (0x10001)
* X509v3 extensions:
* X509v3 Subject Key Identifier:
* FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
* X509v3 Authority Key Identifier:
* keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14
* DirName:/C=US/ST=Some-State/L=Some-City/O=Some-Org
* serial:00
*
* X509v3 Basic Constraints:
* CA:TRUE
* Signature Algorithm: md5WithRSAEncryption
*
* -----BEGIN CERTIFICATE-----
* MIICrDCCAhWgAwIBAgIBADANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET
* MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK
* EwhTb21lLU9yZzAeFw0wODEyMDgwMjQzMzZaFw0yODA4MjUwMjQzMzZaMEkxCzAJ
* BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp
* dHkxETAPBgNVBAoTCFNvbWUtT3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
* gQDLxDggB76Ip5OwoUNRLdeOha9U3a2ieyNbz5kTU5lFfe5tui2/461uPZ8a+QOX
* 4BdVrhEmV94BKY4FPyH35zboLjfXSKxT1mAOx1Bt9sWF94umxZE1cjyU7vEX8HHj
* 7BvOyk5AQrBt7moO1uWtPA/JuoJPePiJl4kqlRJM2Akq6QIDAQABo4GjMIGgMB0G
* A1UdDgQWBBT6uVG/TOfZhpgz+efLHvEzSfeoFDBxBgNVHSMEajBogBT6uVG/TOfZ
* hpgz+efLHvEzSfeoFKFNpEswSTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUt
* U3RhdGUxEjAQBgNVBAcTCVNvbWUtQ2l0eTERMA8GA1UEChMIU29tZS1PcmeCAQAw
* DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBcIm534U123Hz+rtyYO5uA
* ofd81G6FnTfEAV8Kw9fGyyEbQZclBv34A9JsFKeMvU4OFIaixD7nLZ/NZ+IWbhmZ
* LovmJXyCkOufea73pNiZ+f/4/ScZaIlM/PRycQSqbFNd4j9Wott+08qxHPLpsf3P
* 6Mvf0r1PNTY2hwTJLJmKtg==
* -----END CERTIFICATE---
*/
public class PKIXExtendedTM {
/*
* =============================================================
* Set the various variables needed for the tests, then
* specify what tests to run on each side.
*/
/*
* Should we run the client or server in a separate thread?
* Both sides can throw exceptions, but do you have a preference
* as to which side should be the main thread.
*/
static boolean separateServerThread = true;
/*
* Where do we find the keystores?
*/
static String trusedCertStr =
"-----BEGIN CERTIFICATE-----\n" +
"MIICrDCCAhWgAwIBAgIBADANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" +
"MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" +
"EwhTb21lLU9yZzAeFw0wODEyMDgwMjQzMzZaFw0yODA4MjUwMjQzMzZaMEkxCzAJ\n" +
"BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" +
"dHkxETAPBgNVBAoTCFNvbWUtT3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" +
"gQDLxDggB76Ip5OwoUNRLdeOha9U3a2ieyNbz5kTU5lFfe5tui2/461uPZ8a+QOX\n" +
"4BdVrhEmV94BKY4FPyH35zboLjfXSKxT1mAOx1Bt9sWF94umxZE1cjyU7vEX8HHj\n" +
"7BvOyk5AQrBt7moO1uWtPA/JuoJPePiJl4kqlRJM2Akq6QIDAQABo4GjMIGgMB0G\n" +
"A1UdDgQWBBT6uVG/TOfZhpgz+efLHvEzSfeoFDBxBgNVHSMEajBogBT6uVG/TOfZ\n" +
"hpgz+efLHvEzSfeoFKFNpEswSTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUt\n" +
"U3RhdGUxEjAQBgNVBAcTCVNvbWUtQ2l0eTERMA8GA1UEChMIU29tZS1PcmeCAQAw\n" +
"DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBcIm534U123Hz+rtyYO5uA\n" +
"ofd81G6FnTfEAV8Kw9fGyyEbQZclBv34A9JsFKeMvU4OFIaixD7nLZ/NZ+IWbhmZ\n" +
"LovmJXyCkOufea73pNiZ+f/4/ScZaIlM/PRycQSqbFNd4j9Wott+08qxHPLpsf3P\n" +
"6Mvf0r1PNTY2hwTJLJmKtg==\n" +
"-----END CERTIFICATE-----";
static String serverCertStr =
"-----BEGIN CERTIFICATE-----\n" +
"MIICpDCCAg2gAwIBAgIBCDANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" +
"MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" +
"EwhTb21lLU9yZzAeFw0wODEyMDgwMzQzMDRaFw0yODA4MjUwMzQzMDRaMHIxCzAJ\n" +
"BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" +
"dHkxETAPBgNVBAoTCFNvbWUtT3JnMRMwEQYDVQQLEwpTU0wtU2VydmVyMRIwEAYD\n" +
"VQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKWsWxw3\n" +
"ot2ZiS2yebiP1Uil5xyEF41pnMasbfnyHR85GdrTch5u7ETMcKTcugAw9qBPPVR6\n" +
"YWrMV9AKf5UoGD+a2ZTyG8gkiH7+nQ89+1dTCLMgM9Q/F0cU0c3qCNgOdU6vvszS\n" +
"7K+peknfwtmsuCRAkKYDVirQMAVALE+r2XSJAgMBAAGjczBxMAkGA1UdEwQCMAAw\n" +
"CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTtbtv0tVbI+xoGYT8PCLumBNgWVDAfBgNV\n" +
"HSMEGDAWgBT6uVG/TOfZhpgz+efLHvEzSfeoFDAXBgNVHREBAf8EDTALgglsb2Nh\n" +
"bGhvc3QwDQYJKoZIhvcNAQEEBQADgYEAoqVTciHtcvsUj+YaTct8tUh3aTCsKsac\n" +
"PHhfQ+ObjiXSgxsKYTX7ym/wk/wvlbUcbqLKxsu7qrcJitH+H9heV1hEHEu65Uoi\n" +
"nRugFruyOrwvAylV8Cm2af7ddilmYJ+sdJA6N2M3xJRxR0G2LFHEXDNEjYReyexn\n" +
"JqCpf5uZGOo=\n" +
"-----END CERTIFICATE-----";
static String clientCertStr =
"-----BEGIN CERTIFICATE-----\n" +
"MIICpDCCAg2gAwIBAgIBCTANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" +
"MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" +
"EwhTb21lLU9yZzAeFw0wODEyMDgwMzQzMjRaFw0yODA4MjUwMzQzMjRaMHIxCzAJ\n" +
"BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" +
"dHkxETAPBgNVBAoTCFNvbWUtT3JnMRMwEQYDVQQLEwpTU0wtQ2xpZW50MRIwEAYD\n" +
"VQQDEwlsb2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALvwQDas\n" +
"JlRO9KNaAC9pIW+5ejqT7KL24Y7HY9gvEjCZLrDyj/gnLSR4KIT3Ab+NRHndO9JV\n" +
"8848slshfe/9M0qxo//GyJu5D3xBNZf52zoFYAUVr1kXkqMQrRYc5AdTr6h2olYq\n" +
"ktP5KOB4z14fSKtcGd3hZ0O6dY31gqxDkkQbAgMBAAGjczBxMAkGA1UdEwQCMAAw\n" +
"CwYDVR0PBAQDAgXgMB0GA1UdDgQWBBTNu8iFqpG9/R2+zWd8/7PpTKgi5jAfBgNV\n" +
"HSMEGDAWgBT6uVG/TOfZhpgz+efLHvEzSfeoFDAXBgNVHREBAf8EDTALgglsb2Nh\n" +
"bGhvc3QwDQYJKoZIhvcNAQEEBQADgYEAm25gJyqW1JznQ1EyOtTGswBVwfgBOf+F\n" +
"HJuBTcflYQLbTD/AETPQJGvZU9tdhuLtbG3OPhR7vSY8zeAbfM3dbH7QFr3r47Gj\n" +
"XEH7qM/MX+Z3ifVaC4MeJmrYQkYFSuKeyyKpdRVX4w4nnFHF6OsNASsYrMW6LpxN\n" +
"cl/epUcHL7E=\n" +
"-----END CERTIFICATE-----";
static byte serverPrivateExponent[] = {
(byte)0x6e, (byte)0xa7, (byte)0x1b, (byte)0x83,
(byte)0x51, (byte)0x35, (byte)0x9a, (byte)0x44,
(byte)0x7d, (byte)0xf6, (byte)0xe3, (byte)0x89,
(byte)0xa0, (byte)0xd7, (byte)0x90, (byte)0x60,
(byte)0xa1, (byte)0x4e, (byte)0x27, (byte)0x21,
(byte)0xa2, (byte)0x89, (byte)0x74, (byte)0xcc,
(byte)0x9d, (byte)0x75, (byte)0x75, (byte)0x4e,
(byte)0xc7, (byte)0x82, (byte)0xe3, (byte)0xe3,
(byte)0xc3, (byte)0x7d, (byte)0x00, (byte)0x54,
(byte)0xec, (byte)0x36, (byte)0xb1, (byte)0xdf,
(byte)0x91, (byte)0x9c, (byte)0x7a, (byte)0xc0,
(byte)0x62, (byte)0x0a, (byte)0xd6, (byte)0xa9,
(byte)0x22, (byte)0x91, (byte)0x4a, (byte)0x29,
(byte)0x2e, (byte)0x43, (byte)0xfa, (byte)0x8c,
(byte)0xd8, (byte)0xe9, (byte)0xbe, (byte)0xd9,
(byte)0x4f, (byte)0xca, (byte)0x23, (byte)0xc6,
(byte)0xe4, (byte)0x3f, (byte)0xb8, (byte)0x72,
(byte)0xcf, (byte)0x02, (byte)0xfc, (byte)0xf4,
(byte)0x58, (byte)0x34, (byte)0x77, (byte)0x76,
(byte)0xce, (byte)0x22, (byte)0x44, (byte)0x5f,
(byte)0x2d, (byte)0xca, (byte)0xee, (byte)0xf5,
(byte)0x43, (byte)0x56, (byte)0x47, (byte)0x71,
(byte)0x0b, (byte)0x09, (byte)0x6b, (byte)0x5e,
(byte)0xf2, (byte)0xc8, (byte)0xee, (byte)0xd4,
(byte)0x6e, (byte)0x44, (byte)0x92, (byte)0x2a,
(byte)0x7f, (byte)0xcc, (byte)0xa7, (byte)0xd4,
(byte)0x5b, (byte)0xfb, (byte)0xf7, (byte)0x4a,
(byte)0xa9, (byte)0xfb, (byte)0x54, (byte)0x18,
(byte)0xd5, (byte)0xd5, (byte)0x14, (byte)0xba,
(byte)0xa0, (byte)0x1c, (byte)0x13, (byte)0xb3,
(byte)0x37, (byte)0x6b, (byte)0x37, (byte)0x59,
(byte)0xed, (byte)0xdb, (byte)0x6d, (byte)0xb1
};
static byte serverModulus[] = {
(byte)0x00,
(byte)0xa5, (byte)0xac, (byte)0x5b, (byte)0x1c,
(byte)0x37, (byte)0xa2, (byte)0xdd, (byte)0x99,
(byte)0x89, (byte)0x2d, (byte)0xb2, (byte)0x79,
(byte)0xb8, (byte)0x8f, (byte)0xd5, (byte)0x48,
(byte)0xa5, (byte)0xe7, (byte)0x1c, (byte)0x84,
(byte)0x17, (byte)0x8d, (byte)0x69, (byte)0x9c,
(byte)0xc6, (byte)0xac, (byte)0x6d, (byte)0xf9,
(byte)0xf2, (byte)0x1d, (byte)0x1f, (byte)0x39,
(byte)0x19, (byte)0xda, (byte)0xd3, (byte)0x72,
(byte)0x1e, (byte)0x6e, (byte)0xec, (byte)0x44,
(byte)0xcc, (byte)0x70, (byte)0xa4, (byte)0xdc,
(byte)0xba, (byte)0x00, (byte)0x30, (byte)0xf6,
(byte)0xa0, (byte)0x4f, (byte)0x3d, (byte)0x54,
(byte)0x7a, (byte)0x61, (byte)0x6a, (byte)0xcc,
(byte)0x57, (byte)0xd0, (byte)0x0a, (byte)0x7f,
(byte)0x95, (byte)0x28, (byte)0x18, (byte)0x3f,
(byte)0x9a, (byte)0xd9, (byte)0x94, (byte)0xf2,
(byte)0x1b, (byte)0xc8, (byte)0x24, (byte)0x88,
(byte)0x7e, (byte)0xfe, (byte)0x9d, (byte)0x0f,
(byte)0x3d, (byte)0xfb, (byte)0x57, (byte)0x53,
(byte)0x08, (byte)0xb3, (byte)0x20, (byte)0x33,
(byte)0xd4, (byte)0x3f, (byte)0x17, (byte)0x47,
(byte)0x14, (byte)0xd1, (byte)0xcd, (byte)0xea,
(byte)0x08, (byte)0xd8, (byte)0x0e, (byte)0x75,
(byte)0x4e, (byte)0xaf, (byte)0xbe, (byte)0xcc,
(byte)0xd2, (byte)0xec, (byte)0xaf, (byte)0xa9,
(byte)0x7a, (byte)0x49, (byte)0xdf, (byte)0xc2,
(byte)0xd9, (byte)0xac, (byte)0xb8, (byte)0x24,
(byte)0x40, (byte)0x90, (byte)0xa6, (byte)0x03,
(byte)0x56, (byte)0x2a, (byte)0xd0, (byte)0x30,
(byte)0x05, (byte)0x40, (byte)0x2c, (byte)0x4f,
(byte)0xab, (byte)0xd9, (byte)0x74, (byte)0x89
};
static byte clientPrivateExponent[] = {
(byte)0x11, (byte)0xb7, (byte)0x6a, (byte)0x36,
(byte)0x3d, (byte)0x30, (byte)0x37, (byte)0xce,
(byte)0x61, (byte)0x9d, (byte)0x6c, (byte)0x84,
(byte)0x8b, (byte)0xf3, (byte)0x9b, (byte)0x25,
(byte)0x4f, (byte)0x14, (byte)0xc8, (byte)0xa4,
(byte)0xdd, (byte)0x2f, (byte)0xd7, (byte)0x9a,
(byte)0x17, (byte)0xbd, (byte)0x90, (byte)0x19,
(byte)0xf7, (byte)0x05, (byte)0xfd, (byte)0xf2,
(byte)0xd2, (byte)0xc5, (byte)0xf7, (byte)0x77,
(byte)0xbe, (byte)0xea, (byte)0xe2, (byte)0x84,
(byte)0x87, (byte)0x97, (byte)0x3a, (byte)0x41,
(byte)0x96, (byte)0xb6, (byte)0x99, (byte)0xf8,
(byte)0x94, (byte)0x8c, (byte)0x58, (byte)0x71,
(byte)0x51, (byte)0x8c, (byte)0xf4, (byte)0x2a,
(byte)0x20, (byte)0x9e, (byte)0x1a, (byte)0xa0,
(byte)0x26, (byte)0x99, (byte)0x75, (byte)0xd6,
(byte)0x31, (byte)0x53, (byte)0x43, (byte)0x39,
(byte)0xf5, (byte)0x2a, (byte)0xa6, (byte)0x7e,
(byte)0x34, (byte)0x42, (byte)0x51, (byte)0x2a,
(byte)0x40, (byte)0x87, (byte)0x03, (byte)0x88,
(byte)0x43, (byte)0x69, (byte)0xb2, (byte)0x89,
(byte)0x6d, (byte)0x20, (byte)0xbd, (byte)0x7d,
(byte)0x71, (byte)0xef, (byte)0x47, (byte)0x0a,
(byte)0xdf, (byte)0x06, (byte)0xc1, (byte)0x69,
(byte)0x66, (byte)0xa8, (byte)0x22, (byte)0x37,
(byte)0x1a, (byte)0x77, (byte)0x1e, (byte)0xc7,
(byte)0x94, (byte)0x4e, (byte)0x2c, (byte)0x27,
(byte)0x69, (byte)0x45, (byte)0x5e, (byte)0xc8,
(byte)0xf8, (byte)0x0c, (byte)0xb7, (byte)0xf8,
(byte)0xc0, (byte)0x8f, (byte)0x99, (byte)0xc1,
(byte)0xe5, (byte)0x28, (byte)0x9b, (byte)0xf9,
(byte)0x4c, (byte)0x94, (byte)0xc6, (byte)0xb1
};
static byte clientModulus[] = {
(byte)0x00,
(byte)0xbb, (byte)0xf0, (byte)0x40, (byte)0x36,
(byte)0xac, (byte)0x26, (byte)0x54, (byte)0x4e,
(byte)0xf4, (byte)0xa3, (byte)0x5a, (byte)0x00,
(byte)0x2f, (byte)0x69, (byte)0x21, (byte)0x6f,
(byte)0xb9, (byte)0x7a, (byte)0x3a, (byte)0x93,
(byte)0xec, (byte)0xa2, (byte)0xf6, (byte)0xe1,
(byte)0x8e, (byte)0xc7, (byte)0x63, (byte)0xd8,
(byte)0x2f, (byte)0x12, (byte)0x30, (byte)0x99,
(byte)0x2e, (byte)0xb0, (byte)0xf2, (byte)0x8f,
(byte)0xf8, (byte)0x27, (byte)0x2d, (byte)0x24,
(byte)0x78, (byte)0x28, (byte)0x84, (byte)0xf7,
(byte)0x01, (byte)0xbf, (byte)0x8d, (byte)0x44,
(byte)0x79, (byte)0xdd, (byte)0x3b, (byte)0xd2,
(byte)0x55, (byte)0xf3, (byte)0xce, (byte)0x3c,
(byte)0xb2, (byte)0x5b, (byte)0x21, (byte)0x7d,
(byte)0xef, (byte)0xfd, (byte)0x33, (byte)0x4a,
(byte)0xb1, (byte)0xa3, (byte)0xff, (byte)0xc6,
(byte)0xc8, (byte)0x9b, (byte)0xb9, (byte)0x0f,
(byte)0x7c, (byte)0x41, (byte)0x35, (byte)0x97,
(byte)0xf9, (byte)0xdb, (byte)0x3a, (byte)0x05,
(byte)0x60, (byte)0x05, (byte)0x15, (byte)0xaf,
(byte)0x59, (byte)0x17, (byte)0x92, (byte)0xa3,
(byte)0x10, (byte)0xad, (byte)0x16, (byte)0x1c,
(byte)0xe4, (byte)0x07, (byte)0x53, (byte)0xaf,
(byte)0xa8, (byte)0x76, (byte)0xa2, (byte)0x56,
(byte)0x2a, (byte)0x92, (byte)0xd3, (byte)0xf9,
(byte)0x28, (byte)0xe0, (byte)0x78, (byte)0xcf,
(byte)0x5e, (byte)0x1f, (byte)0x48, (byte)0xab,
(byte)0x5c, (byte)0x19, (byte)0xdd, (byte)0xe1,
(byte)0x67, (byte)0x43, (byte)0xba, (byte)0x75,
(byte)0x8d, (byte)0xf5, (byte)0x82, (byte)0xac,
(byte)0x43, (byte)0x92, (byte)0x44, (byte)0x1b
};
static char passphrase[] = "passphrase".toCharArray();
/*
* Is the server ready to serve?
*/
volatile static boolean serverReady = false;
/*
* Turn on SSL debugging?
*/
static boolean debug = false;
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
SSLContext context = getSSLContext(trusedCertStr, serverCertStr,
serverModulus, serverPrivateExponent, passphrase);
SSLServerSocketFactory sslssf = context.getServerSocketFactory();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort);
serverPort = sslServerSocket.getLocalPort();
// enable endpoint identification
// ignore, we may test the feature when known how to parse client
// hostname
//SSLParameters params = sslServerSocket.getSSLParameters();
//params.setEndpointIdentificationAlgorithm("HTTPS");
//sslServerSocket.setSSLParameters(params);
/*
* Signal Client, we're ready for his connect.
*/
serverReady = true;
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
sslSocket.setNeedClientAuth(true);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslIS.read();
sslOS.write(85);
sslOS.flush();
sslSocket.close();
}
/*
* Define the client side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doClientSide() throws Exception {
/*
* Wait for server to get started.
*/
while (!serverReady) {
Thread.sleep(50);
}
SSLContext context = getSSLContext(trusedCertStr, clientCertStr,
clientModulus, clientPrivateExponent, passphrase);
SSLSocketFactory sslsf = context.getSocketFactory();
SSLSocket sslSocket = (SSLSocket)
sslsf.createSocket("localhost", serverPort);
// enable endpoint identification
SSLParameters params = sslSocket.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS");
sslSocket.setSSLParameters(params);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslOS.write(280);
sslOS.flush();
sslIS.read();
sslSocket.close();
}
// get the ssl context
private static SSLContext getSSLContext(String trusedCertStr,
String keyCertStr, byte[] modulus,
byte[] privateExponent, char[] passphrase) throws Exception {
// generate certificate from cert string
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream is =
new ByteArrayInputStream(trusedCertStr.getBytes());
Certificate trusedCert = cf.generateCertificate(is);
is.close();
// create a key store
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
// import the trused cert
ks.setCertificateEntry("RSA Export Signer", trusedCert);
if (keyCertStr != null) {
// generate the private key.
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
new BigInteger(modulus),
new BigInteger(privateExponent));
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey priKey =
(RSAPrivateKey)kf.generatePrivate(priKeySpec);
// generate certificate chain
is = new ByteArrayInputStream(keyCertStr.getBytes());
Certificate keyCert = cf.generateCertificate(is);
is.close();
Certificate[] chain = new Certificate[2];
chain[0] = keyCert;
chain[1] = trusedCert;
// import the key entry.
ks.setKeyEntry("Whatever", priKey, passphrase, chain);
}
// create SSL context
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
if (tms == null || tms.length == 0) {
throw new Exception("unexpected trust manager implementation");
} else {
if (!(tms[0] instanceof X509ExtendedTrustManager)) {
throw new Exception("unexpected trust manager implementation: "
+ tms[0].getClass().getCanonicalName());
}
}
SSLContext ctx = SSLContext.getInstance("TLS");
if (keyCertStr != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} else {
ctx.init(null, tmf.getTrustManagers(), null);
}
return ctx;
}
/*
* =============================================================
* The remainder is just support stuff
*/
// use any free port by default
volatile int serverPort = 0;
volatile Exception serverException = null;
volatile Exception clientException = null;
public static void main(String args[]) throws Exception {
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new PKIXExtendedTM();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
PKIXExtendedTM() throws Exception {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
serverThread.join();
} else {
clientThread.join();
}
/*
* When we get here, the test is pretty much over.
*
* If the main thread excepted, that propagates back
* immediately. If the other thread threw an exception, we
* should report back.
*/
if (serverException != null)
throw serverException;
if (clientException != null)
throw clientException;
}
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*
* Release the client, if not active already...
*/
System.err.println("Server died...");
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
doServerSide();
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
doClientSide();
}
}
}
|
apache/solr | 37,593 | solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/stream/CloudAuthStreamTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.io.stream;
import static org.apache.solr.security.Sha256AuthenticationProvider.getSaltedHashedValue;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.io.Tuple;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.common.util.Utils;
import org.apache.solr.security.BasicAuthPlugin;
import org.apache.solr.security.RuleBasedAuthorizationPlugin;
import org.apache.solr.util.TimeOut;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* tests various streaming expressions (via the SolrJ {@link SolrStream} API) against a SolrCloud
* cluster using both Authentication and Role based Authorization
*/
public class CloudAuthStreamTest extends SolrCloudTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String COLLECTION_X = "collection_x";
private static final String COLLECTION_Y = "collection_y";
private static final String READ_ONLY_USER = "read_only_user";
private static final String WRITE_X_USER = "write_x_user";
private static final String WRITE_Y_USER = "write_y_user";
private static final String ADMIN_USER = "admin_user";
private static String solrUrl = null;
/**
* Helper that returns the original {@link SolrRequest} <em>with its original type</em> so it can
* be chained. This method knows that for the purpose of this test, every username is its own
* password
*
* @see SolrRequest#setBasicAuthCredentials
*/
private static <T extends SolrRequest<?>> T setBasicAuthCredentials(T req, String user) {
assertNotNull(user);
req.setBasicAuthCredentials(user, user);
return req;
}
@BeforeClass
public static void setupCluster() throws Exception {
final List<String> users =
Arrays.asList(READ_ONLY_USER, WRITE_X_USER, WRITE_Y_USER, ADMIN_USER);
// For simplicity: every user uses a password the same as their name...
final Map<String, String> credentials =
users.stream().collect(Collectors.toMap(Function.identity(), s -> getSaltedHashedValue(s)));
// For simplicity: Every user is their own role...
final Map<String, String> roles =
users.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));
final String SECURITY_JSON =
Utils.toJSONString(
Map.of(
"authorization",
Map.of(
"class",
RuleBasedAuthorizationPlugin.class.getName(),
"user-role",
roles,
// NOTE: permissions order matters!
"permissions",
Arrays.asList( // any authn user can 'read' or hit /stream
Map.of("name", "read", "role", "*"),
Map.of("name", "stream", "collection", "*", "path", "/stream", "role", "*"),
// per collection write perms
Map.of("name", "update", "collection", COLLECTION_X, "role", WRITE_X_USER),
Map.of("name", "update", "collection", COLLECTION_Y, "role", WRITE_Y_USER),
Map.of("name", "all", "role", ADMIN_USER))),
"authentication",
Map.of(
"class",
BasicAuthPlugin.class.getName(),
"blockUnknown",
true,
"credentials",
credentials)));
// we want at most one core per node to force lots of network traffic to try and tickle
// distributed bugs
configureCluster(5).withSecurityJson(SECURITY_JSON).configure();
for (String collection : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
CollectionAdminRequest.createCollection(collection, "_default", 2, 2)
.setBasicAuthCredentials(ADMIN_USER, ADMIN_USER)
.process(cluster.getSolrClient());
}
for (String collection : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
cluster
.getZkStateReader()
.waitForState(
collection,
DEFAULT_TIMEOUT,
TimeUnit.SECONDS,
(n, c) -> DocCollection.isFullyActive(n, c, 2, 2));
}
solrUrl = cluster.getRandomJetty(random()).getProxyBaseUrl().toString();
log.info("All stream requests will be sent to random solrUrl: {}", solrUrl);
}
@AfterClass
public static void clearVariables() {
solrUrl = null;
}
@After
public void clearCollections() throws Exception {
log.info("Clearing Collections @After test method...");
assertEquals(
0,
setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.deleteByQuery("*:*")
.commit(cluster.getSolrClient(), COLLECTION_X)
.getStatus());
assertEquals(
0,
setBasicAuthCredentials(new UpdateRequest(), WRITE_Y_USER)
.deleteByQuery("*:*")
.commit(cluster.getSolrClient(), COLLECTION_Y)
.getStatus());
}
/** Simple sanity checks that authentication is working the way the test expects */
public void testSanityCheckAuth() throws Exception {
assertEquals(
"sanity check of non authenticated query request",
401,
expectThrows(
SolrException.class,
() -> {
final long ignored =
(new QueryRequest(
params(
"q", "*:*",
"rows", "0",
"_trace", "no_auth_sanity_check")))
.process(cluster.getSolrClient(), COLLECTION_X)
.getResults()
.getNumFound();
})
.code());
assertEquals(
"sanity check of update to X from write_X user",
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.add(sdoc("id", "1_from_write_X_user"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus());
assertEquals(
"sanity check of update to X from read only user",
403,
expectThrows(
SolrException.class,
() -> {
final int ignored =
(setBasicAuthCredentials(new UpdateRequest(), READ_ONLY_USER)
.add(sdoc("id", "2_from_read_only_user"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus();
})
.code());
assertEquals(
"sanity check of update to X from write_Y user",
403,
expectThrows(
SolrException.class,
() -> {
final int ignored =
(setBasicAuthCredentials(new UpdateRequest(), WRITE_Y_USER)
.add(sdoc("id", "3_from_write_Y_user"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus();
})
.code());
assertEquals(
"sanity check of update to Y from write_Y user",
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_Y_USER)
.add(sdoc("id", "1_from_write_Y_user"))
.commit(cluster.getSolrClient(), COLLECTION_Y))
.getStatus());
for (String user : Arrays.asList(READ_ONLY_USER, WRITE_Y_USER, WRITE_X_USER)) {
for (String collection : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
assertEquals(
"sanity check: query " + collection + " from user: " + user,
1,
countDocsInCollection(collection, user));
}
}
}
public void testEchoStream() throws Exception {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt", "/stream",
"expr", "echo(hello world)"));
solrStream.setCredentials(READ_ONLY_USER, READ_ONLY_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals("hello world", tuples.get(0).get("echo"));
}
public void testEchoStreamNoCredentials() {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt", "/stream",
"expr", "echo(hello world)"));
// NOTE: no credentials
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
public void testEchoStreamInvalidCredentials() {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt", "/stream",
"expr", "echo(hello world)"));
solrStream.setCredentials(READ_ONLY_USER, "BOGUS_PASSWORD");
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
public void testSimpleUpdateStream() throws Exception {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42,a_i=1,b_i=5))"));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(1L, tuples.get(0).get("totalIndexed"));
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testSimpleUpdateStreamInvalidCredentials() throws Exception {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42,a_i=1,b_i=5))"));
// "WRITE" credentials should be required for 'update(...)'
solrStream.setCredentials(WRITE_X_USER, "BOGUS_PASSWORD");
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
assertEquals(0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testSimpleUpdateStreamInsufficientCredentials() throws Exception {
// both of these users have valid credentials and authz read COLLECTION_X, but neither has
// authz to write to X...
for (String user : Arrays.asList(READ_ONLY_USER, WRITE_Y_USER)) {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42,a_i=1,b_i=5))"));
solrStream.setCredentials(user, user);
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
assertEquals(0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testIndirectUpdateStream() throws Exception {
{ // WRITE_X user should be able to update X via a (dummy) stream from Y...
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_Y,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42,a_i=1,b_i=5))"));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(1L, tuples.get(0).get("totalIndexed"));
}
{ // Now add some "real" docs directly to Y...
final UpdateRequest update = setBasicAuthCredentials(new UpdateRequest(), WRITE_Y_USER);
for (int i = 1; i <= 42; i++) {
update.add(sdoc("id", i + "y", "foo_i", "" + i));
}
assertEquals(
"initial docs in Y", 0, update.commit(cluster.getSolrClient(), COLLECTION_Y).getStatus());
}
{ // WRITE_X user should be able to update X via a (search) stream from Y (routed via Y)
// note batch size - 10 matches = 1 batch
// pruneVersionField default true
final String expr =
"update("
+ COLLECTION_X
+ ", batchSize=50, search("
+ COLLECTION_Y
+ ", q=\"foo_i:[* TO 10]\", rows=100, fl=\"id,foo_i,_version_\", sort=\"foo_i desc\"))";
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_Y, // NOTE: Y route
params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(10L, tuples.get(0).get("batchIndexed"));
assertEquals(10L, tuples.get(0).get("totalIndexed"));
}
{ // WRITE_X user should be able to update X via a (search) stream from Y (routed via X)...
// note batch size - 13 matches = 3 batches
final String expr =
"update("
+ COLLECTION_X
+ ", batchSize=5, search("
+ COLLECTION_Y
+ ", q=\"foo_i:[30 TO *]\", rows=100, fl=\"id,foo_i\", sort=\"foo_i desc\"))";
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X, // NOTE: X route
params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(3, tuples.size());
assertEquals(5L, tuples.get(0).get("batchIndexed"));
assertEquals(5L, tuples.get(0).get("totalIndexed"));
assertEquals(5L, tuples.get(1).get("batchIndexed"));
assertEquals(10L, tuples.get(1).get("totalIndexed"));
assertEquals(3L, tuples.get(2).get("batchIndexed"));
assertEquals(13L, tuples.get(2).get("totalIndexed"));
}
assertEquals(1L + 10L + 13L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testIndirectUpdateStreamInsufficientCredentials() throws Exception {
// regardless of how it's routed, WRITE_Y should NOT have authz to stream updates to X...
for (String path : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + path,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42,a_i=1,b_i=5))"));
solrStream.setCredentials(WRITE_Y_USER, WRITE_Y_USER);
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
assertEquals(0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testExecutorUpdateStream() throws Exception {
final String expr =
"executor(threads=1, tuple(expr_s=\"update("
+ COLLECTION_X
+ ", batchSize=5, tuple(id=42,a_i=1,b_i=5))\"))";
final SolrStream solrStream =
new SolrStream(solrUrl + "/" + COLLECTION_X, params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(0, tuples.size());
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testExecutorUpdateStreamInsufficientCredentials() throws Exception {
int id = 0;
// both of these users have valid credentials and authz read COLLECTION_X, but neither has
// authz to write to X...
for (String user : Arrays.asList(READ_ONLY_USER, WRITE_Y_USER)) {
// ... regardless of how the request is routed...
for (String path : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
final String trace = user + ":" + path;
final String expr =
"executor(threads=1,tuple(expr_s=\"update("
+ COLLECTION_X
+ ", batchSize=5,tuple(id='"
+ (++id)
+ "',foo_s='"
+ trace
+ "'))\"))";
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + path,
params("qt", "/stream", "_trace", "executor_via_" + trace, "expr", expr));
solrStream.setCredentials(user, user);
// NOTE: Because of the background threads, no failures will to be returned to client...
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(0, tuples.size());
// we have to assert that the updates failed solely based on the side effects...
assertEquals(
"doc count after execute update via " + trace,
0L,
commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
}
// sanity check
assertEquals("final doc count", 0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testDaemonUpdateStream() throws Exception {
final String daemonUrl = getRandomCoreUrl(COLLECTION_X);
log.info("Using Daemon @ {}", daemonUrl);
{
// NOTE: in spite of what is implied by 'terminate=true', this daemon will NEVER terminate on
// its own as long as the updates are successful (apparently that requires usage of a topic()
// stream to set a "sleepMillis"?!)
final String expr =
"daemon(id=daemonId,runInterval=1000,terminate=true,update("
+ COLLECTION_X
+ ",tuple(id=42,a_i=1,b_i=5)))";
final SolrStream solrStream =
new SolrStream(daemonUrl, params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size()); // daemon starting status
}
try {
// We have to poll the daemon 'list' to know once it's run...
long iterations = 0;
final TimeOut timeout = new TimeOut(60, TimeUnit.SECONDS, TimeSource.NANO_TIME);
while (!timeout.hasTimedOut()) {
final SolrStream daemonCheck =
new SolrStream(
daemonUrl,
params(
"qt", "/stream",
"action", "list"));
daemonCheck.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(daemonCheck);
assertEquals(1, tuples.size()); // our daemon;
iterations = tuples.get(0).getLong("iterations");
if (1 < iterations) {
// once the daemon has had a chance to run, break out of TimeOut
break;
}
Thread.sleep(Math.max(1, Math.min(5000, timeout.timeLeft(TimeUnit.MILLISECONDS))));
}
assertTrue(
"Didn't see any iterations after waiting an excessive amount of time: " + iterations,
0 < iterations);
} finally {
// kill the damon...
final SolrStream daemonKiller =
new SolrStream(
daemonUrl,
params(
"qt", "/stream",
"action", "kill",
"id", "daemonId"));
daemonKiller.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(daemonKiller);
assertEquals(1, tuples.size()); // daemon death status
}
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testDaemonUpdateStreamInsufficientCredentials() throws Exception {
final String daemonUrl = getRandomCoreUrl(COLLECTION_X);
log.info("Using Daemon @ {}", daemonUrl);
// both of these users have valid credentials and authz read COLLECTION_X, but neither has
// authz to write to X...
for (String user : Arrays.asList(READ_ONLY_USER, WRITE_Y_USER)) {
final String daemonId = "daemon_" + user;
{
final String expr =
"daemon(id="
+ daemonId
+ ",runInterval=1000,terminate=true, "
+ " update("
+ COLLECTION_X
+ ",tuple(id=42,a_i=1,b_i=5))) ";
final SolrStream solrStream =
new SolrStream(
daemonUrl, params("qt", "/stream", "_trace", "start_" + daemonId, "expr", expr));
solrStream.setCredentials(user, user);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size()); // daemon starting status
}
try {
// We have to poll the daemon 'list' to know once it's run / terminated...
Object state = null;
final TimeOut timeout = new TimeOut(60, TimeUnit.SECONDS, TimeSource.NANO_TIME);
while (!timeout.hasTimedOut()) {
final SolrStream daemonCheck =
new SolrStream(
daemonUrl,
params(
"qt", "/stream",
"_trace", "check_" + daemonId,
"action", "list"));
daemonCheck.setCredentials(user, user);
final List<Tuple> tuples = getTuples(daemonCheck);
assertEquals(1, tuples.size()); // our daemon;
if (log.isInfoEnabled()) {
log.info("Current daemon status: {}", tuples.get(0).getFields());
}
assertEquals(
daemonId + " should have never had a successful iteration",
Long.valueOf(0L),
tuples.get(0).getLong("iterations"));
state = tuples.get(0).get("state");
if ("TERMINATED".equals(state)) {
// once the daemon has failed, break out of TimeOut
break;
}
Thread.sleep(Math.max(1, Math.min(5000, timeout.timeLeft(TimeUnit.MILLISECONDS))));
}
assertEquals(
"Timed out w/o ever getting TERMINATED state from " + daemonId, "TERMINATED", state);
} finally {
// kill the damon...
final SolrStream daemonKiller =
new SolrStream(
daemonUrl,
params(
"qt",
"/stream",
"_trace",
"kill_" + daemonId,
"action",
"kill",
"id",
daemonId));
daemonKiller.setCredentials(user, user);
final List<Tuple> tuples = getTuples(daemonKiller);
assertEquals(1, tuples.size()); // daemon death status
}
assertEquals(
"doc count after daemon update for " + user,
0L,
commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
// sanity check
assertEquals("final doc count", 0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testSimpleDeleteStream() throws Exception {
assertEquals(
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.add(sdoc("id", "42"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus());
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"delete(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42))"));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(1L, tuples.get(0).get("totalIndexed"));
assertEquals(0L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
/** A simple "Delete by Query" example */
public void testSimpleDeleteStreamByQuery() throws Exception {
{ // Put some "real" docs directly to both X...
final UpdateRequest update = setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER);
for (int i = 1; i <= 42; i++) {
update.add(sdoc("id", i + "x", "foo_i", "" + i));
}
assertEquals(
"initial docs in X", 0, update.commit(cluster.getSolrClient(), COLLECTION_X).getStatus());
}
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
{ // WRITE_X user should be able to delete X via a query from X
// note batch size - 10 matches = 2 batches
// foo_i should be ignored...
// version constraint should be ok
final String expr =
"delete("
+ COLLECTION_X
+ ", batchSize=5, search("
+ COLLECTION_X
+ ", q=\"foo_i:[* TO 10]\", rows=100, fl=\"id,foo_i,_version_\", sort=\"foo_i desc\"))";
final SolrStream solrStream =
new SolrStream(solrUrl + "/" + COLLECTION_X, params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(2, tuples.size());
assertEquals(5L, tuples.get(0).get("totalIndexed"));
assertEquals(10L, tuples.get(1).get("totalIndexed"));
}
assertEquals(42L - 10L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testSimpleDeleteStreamInvalidCredentials() throws Exception {
assertEquals(
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.add(sdoc("id", "42"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus());
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42))"));
// "WRITE" credentials should be required for 'update(...)'
solrStream.setCredentials(WRITE_X_USER, "BOGUS_PASSWORD");
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testSimpleDeleteStreamInsufficientCredentials() throws Exception {
assertEquals(
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.add(sdoc("id", "42"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus());
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
// both of these users have valid credentials and authz read COLLECTION_X, but neither has
// authz to write to X...
for (String user : Arrays.asList(READ_ONLY_USER, WRITE_Y_USER)) {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X,
params(
"qt",
"/stream",
"expr",
"update(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42))"));
solrStream.setCredentials(user, user);
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
public void testIndirectDeleteStream() throws Exception {
{ // Put some "real" docs directly to both X & Y...
final UpdateRequest xxx_Update = setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER);
final UpdateRequest yyy_Update = setBasicAuthCredentials(new UpdateRequest(), WRITE_Y_USER);
for (int i = 1; i <= 42; i++) {
xxx_Update.add(sdoc("id", i + "z", "foo_i", "" + i));
yyy_Update.add(sdoc("id", i + "z", "foo_i", "" + i));
}
assertEquals(
"initial docs in X",
0,
xxx_Update.commit(cluster.getSolrClient(), COLLECTION_X).getStatus());
assertEquals(
"initial docs in Y",
0,
yyy_Update.commit(cluster.getSolrClient(), COLLECTION_Y).getStatus());
}
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_Y, WRITE_Y_USER));
{ // WRITE_X user should be able to delete X via a (dummy) stream from Y...
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_Y,
params(
"qt",
"/stream",
"expr",
"delete(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42z))"));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(1L, tuples.get(0).get("totalIndexed"));
}
assertEquals(42L - 1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_Y, WRITE_Y_USER));
{ // WRITE_X user should be able to delete ids from X via a stream from Y (routed via Y)
// note batch size - 10 matches = 1 batch
// NOTE: ignoring Y version to del X
// foo_i & version should be ignored
final String expr =
"delete("
+ COLLECTION_X
+ ", batchSize=50, pruneVersionField=true, search("
+ COLLECTION_Y
+ ", q=\"foo_i:[* TO 10]\", rows=100, fl=\"id,foo_i,_version_\", sort=\"foo_i desc\"))";
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_Y, // NOTE: Y route
params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(1, tuples.size());
assertEquals(10L, tuples.get(0).get("batchIndexed"));
assertEquals(10L, tuples.get(0).get("totalIndexed"));
}
assertEquals(42L - 1L - 10L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_Y, WRITE_Y_USER));
{ // WRITE_X user should be able to delete ids from X via a stream from Y (routed via X)...
// note batch size - 13 matches = 3 batches
// foo_i should be ignored
final String expr =
"delete("
+ COLLECTION_X
+ ", batchSize=5, search("
+ COLLECTION_Y
+ ", q=\"foo_i:[30 TO *]\", rows=100, fl=\"id,foo_i\", sort=\"foo_i desc\")) ";
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + COLLECTION_X, // NOTE: X route
params("qt", "/stream", "expr", expr));
solrStream.setCredentials(WRITE_X_USER, WRITE_X_USER);
final List<Tuple> tuples = getTuples(solrStream);
assertEquals(3, tuples.size());
assertEquals(5L, tuples.get(0).get("batchIndexed"));
assertEquals(5L, tuples.get(0).get("totalIndexed"));
assertEquals(5L, tuples.get(1).get("batchIndexed"));
assertEquals(10L, tuples.get(1).get("totalIndexed"));
assertEquals(3L, tuples.get(2).get("batchIndexed"));
assertEquals(13L, tuples.get(2).get("totalIndexed"));
}
assertEquals(
42L - 1L - 10L - (13L - 1L), // '42' in last 13 deletes was already deleted from X
commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
assertEquals(42L, commitAndCountDocsInCollection(COLLECTION_Y, WRITE_Y_USER));
}
public void testIndirectDeleteStreamInsufficientCredentials() throws Exception {
assertEquals(
0,
(setBasicAuthCredentials(new UpdateRequest(), WRITE_X_USER)
.add(sdoc("id", "42"))
.commit(cluster.getSolrClient(), COLLECTION_X))
.getStatus());
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
// regardless of how it's routed, WRITE_Y should NOT have authz to delete from X...
for (String path : Arrays.asList(COLLECTION_X, COLLECTION_Y)) {
final SolrStream solrStream =
new SolrStream(
solrUrl + "/" + path,
params(
"qt",
"/stream",
"expr",
"delete(" + COLLECTION_X + ",batchSize=1," + "tuple(id=42))"));
solrStream.setCredentials(WRITE_Y_USER, WRITE_Y_USER);
// NOTE: Can't make any assertions about Exception: SOLR-14226
expectThrows(
Exception.class,
() -> {
final List<Tuple> ignored = getTuples(solrStream);
});
}
assertEquals(1L, commitAndCountDocsInCollection(COLLECTION_X, WRITE_X_USER));
}
/**
* Helper method that uses the specified user to (first commit, and then) count the total number
* of documents in the collection
*/
protected static long commitAndCountDocsInCollection(final String collection, final String user)
throws Exception {
assertEquals(
0,
setBasicAuthCredentials(new UpdateRequest(), user)
.commit(cluster.getSolrClient(), collection)
.getStatus());
return countDocsInCollection(collection, user);
}
/**
* Helper method that uses the specified user to count the total number of documents in the
* collection
*/
protected static long countDocsInCollection(final String collection, final String user)
throws Exception {
return setBasicAuthCredentials(
new QueryRequest(
params(
"q", "*:*",
"rows", "0",
"_trace", "count_via_" + user + ":" + collection)),
user)
.process(cluster.getSolrClient(), collection)
.getResults()
.getNumFound();
}
/** Slurps a stream into a List */
protected static List<Tuple> getTuples(final TupleStream tupleStream) throws IOException {
List<Tuple> tuples = new ArrayList<>();
try {
log.trace("TupleStream: {}", tupleStream);
tupleStream.open();
for (Tuple t = tupleStream.read(); !t.EOF; t = tupleStream.read()) {
if (log.isTraceEnabled()) {
log.trace("Tuple: {}", t.getFields());
}
tuples.add(t);
}
} finally {
tupleStream.close();
}
return tuples;
}
/** Sigh. DaemonStream requires polling the same core where the stream was executed. */
protected static String getRandomCoreUrl(final String collection) {
final List<String> replicaUrls =
cluster
.getZkStateReader()
.getClusterState()
.getCollectionOrNull(collection)
.getReplicas()
.stream()
.map(Replica::getCoreUrl)
.collect(Collectors.toList());
Collections.shuffle(replicaUrls, random());
return replicaUrls.get(0);
}
}
|
google/j2objc | 38,396 | jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ChronoField.java | /*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.temporal;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.FOREVER;
import static java.time.temporal.ChronoUnit.HALF_DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MICROS;
import static java.time.temporal.ChronoUnit.MILLIS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.MONTHS;
import static java.time.temporal.ChronoUnit.NANOS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static java.time.temporal.ChronoUnit.WEEKS;
import static java.time.temporal.ChronoUnit.YEARS;
import android.icu.text.DateTimePatternGenerator;
import android.icu.util.ULocale;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.Year;
import java.time.ZoneOffset;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.Chronology;
import java.util.Locale;
import java.util.Objects;
/**
* A standard set of fields.
* <p>
* This set of fields provide field-based access to manipulate a date, time or date-time.
* The standard set of fields can be extended by implementing {@link TemporalField}.
* <p>
* These fields are intended to be applicable in multiple calendar systems.
* For example, most non-ISO calendar systems define dates as a year, month and day,
* just with slightly different rules.
* The documentation of each field explains how it operates.
*
* @implSpec
* This is a final, immutable and thread-safe enum.
*
* @since 1.8
*/
public enum ChronoField implements TemporalField {
/**
* The nano-of-second.
* <p>
* This counts the nanosecond within the second, from 0 to 999,999,999.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the nano-of-second handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_MINUTE}, {@link #SECOND_OF_DAY} or
* {@link #INSTANT_SECONDS} filling unknown precision with zero.
* <p>
* When this field is used for setting a value, it should set as much precision as the
* object stores, using integer division to remove excess precision.
* For example, if the {@code TemporalAccessor} stores time to millisecond precision,
* then the nano-of-second must be divided by 1,000,000 before replacing the milli-of-second.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The field is resolved in combination with {@code MILLI_OF_SECOND} and {@code MICRO_OF_SECOND}.
*/
NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999)),
/**
* The nano-of-day.
* <p>
* This counts the nanosecond within the day, from 0 to (24 * 60 * 60 * 1,000,000,000) - 1.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the nano-of-day handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_DAY} filling unknown precision with zero.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The value is split to form {@code NANO_OF_SECOND}, {@code SECOND_OF_MINUTE},
* {@code MINUTE_OF_HOUR} and {@code HOUR_OF_DAY} fields.
*/
NANO_OF_DAY("NanoOfDay", NANOS, DAYS, ValueRange.of(0, 86400L * 1000_000_000L - 1)),
/**
* The micro-of-second.
* <p>
* This counts the microsecond within the second, from 0 to 999,999.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the micro-of-second handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_MINUTE}, {@link #SECOND_OF_DAY} or
* {@link #INSTANT_SECONDS} filling unknown precision with zero.
* <p>
* When this field is used for setting a value, it should behave in the same way as
* setting {@link #NANO_OF_SECOND} with the value multiplied by 1,000.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The field is resolved in combination with {@code MILLI_OF_SECOND} to produce
* {@code NANO_OF_SECOND}.
*/
MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, ValueRange.of(0, 999_999)),
/**
* The micro-of-day.
* <p>
* This counts the microsecond within the day, from 0 to (24 * 60 * 60 * 1,000,000) - 1.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the micro-of-day handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_DAY} filling unknown precision with zero.
* <p>
* When this field is used for setting a value, it should behave in the same way as
* setting {@link #NANO_OF_DAY} with the value multiplied by 1,000.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The value is split to form {@code MICRO_OF_SECOND}, {@code SECOND_OF_MINUTE},
* {@code MINUTE_OF_HOUR} and {@code HOUR_OF_DAY} fields.
*/
MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, ValueRange.of(0, 86400L * 1000_000L - 1)),
/**
* The milli-of-second.
* <p>
* This counts the millisecond within the second, from 0 to 999.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the milli-of-second handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_MINUTE}, {@link #SECOND_OF_DAY} or
* {@link #INSTANT_SECONDS} filling unknown precision with zero.
* <p>
* When this field is used for setting a value, it should behave in the same way as
* setting {@link #NANO_OF_SECOND} with the value multiplied by 1,000,000.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The field is resolved in combination with {@code MICRO_OF_SECOND} to produce
* {@code NANO_OF_SECOND}.
*/
MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, ValueRange.of(0, 999)),
/**
* The milli-of-day.
* <p>
* This counts the millisecond within the day, from 0 to (24 * 60 * 60 * 1,000) - 1.
* This field has the same meaning for all calendar systems.
* <p>
* This field is used to represent the milli-of-day handling any fraction of the second.
* Implementations of {@code TemporalAccessor} should provide a value for this field if
* they can return a value for {@link #SECOND_OF_DAY} filling unknown precision with zero.
* <p>
* When this field is used for setting a value, it should behave in the same way as
* setting {@link #NANO_OF_DAY} with the value multiplied by 1,000,000.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The value is split to form {@code MILLI_OF_SECOND}, {@code SECOND_OF_MINUTE},
* {@code MINUTE_OF_HOUR} and {@code HOUR_OF_DAY} fields.
*/
MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, ValueRange.of(0, 86400L * 1000L - 1)),
/**
* The second-of-minute.
* <p>
* This counts the second within the minute, from 0 to 59.
* This field has the same meaning for all calendar systems.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
*/
SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second"),
/**
* The second-of-day.
* <p>
* This counts the second within the day, from 0 to (24 * 60 * 60) - 1.
* This field has the same meaning for all calendar systems.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The value is split to form {@code SECOND_OF_MINUTE}, {@code MINUTE_OF_HOUR}
* and {@code HOUR_OF_DAY} fields.
*/
SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, ValueRange.of(0, 86400L - 1)),
/**
* The minute-of-hour.
* <p>
* This counts the minute within the hour, from 0 to 59.
* This field has the same meaning for all calendar systems.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
*/
MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute"),
/**
* The minute-of-day.
* <p>
* This counts the minute within the day, from 0 to (24 * 60) - 1.
* This field has the same meaning for all calendar systems.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated in strict and smart mode but not in lenient mode.
* The value is split to form {@code MINUTE_OF_HOUR} and {@code HOUR_OF_DAY} fields.
*/
MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, ValueRange.of(0, (24 * 60) - 1)),
/**
* The hour-of-am-pm.
*
* <p>This counts the hour within the AM/PM, from 0 to 11. This is the hour that would be observed
* on a standard 12-hour digital clock. This field has the same meaning for all calendar systems.
*
* <p>When parsing this field it behaves equivalent to the following: The value is validated from
* 0 to 11 in strict and smart mode. In lenient mode the value is not validated. It is combined
* with {@code AMPM_OF_DAY} to form {@code HOUR_OF_DAY} by multiplying the {AMPM_OF_DAY} value by
* 12.
*
* <p>See {@link #CLOCK_HOUR_OF_AMPM} for the related field that counts hours from 1 to 12.
*/
HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(0, 11)),
/**
* The clock-hour-of-am-pm.
*
* <p>This counts the hour within the AM/PM, from 1 to 12. This is the hour that would be observed
* on a standard 12-hour analog wall clock. This field has the same meaning for all calendar
* systems.
*
* <p>When parsing this field it behaves equivalent to the following: The value is validated from
* 1 to 12 in strict mode and from 0 to 12 in smart mode. In lenient mode the value is not
* validated. The field is converted to an {@code HOUR_OF_AMPM} with the same value, unless the
* value is 12, in which case it is converted to 0.
*
* <p>See {@link #HOUR_OF_AMPM} for the related field that counts hours from 0 to 11.
*/
CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12)),
/**
* The hour-of-day.
*
* <p>This counts the hour within the day, from 0 to 23. This is the hour that would be observed
* on a standard 24-hour digital clock. This field has the same meaning for all calendar systems.
*
* <p>When parsing this field it behaves equivalent to the following: The value is validated in
* strict and smart mode but not in lenient mode. The field is combined with {@code
* MINUTE_OF_HOUR}, {@code SECOND_OF_MINUTE} and {@code NANO_OF_SECOND} to produce a {@code
* LocalTime}. In lenient mode, any excess days are added to the parsed date, or made available
* via {@link java.time.format.DateTimeFormatter#parsedExcessDays()}.
*
* <p>See {@link #CLOCK_HOUR_OF_DAY} for the related field that counts hours from 1 to 24.
*/
HOUR_OF_DAY("HourOfDay", HOURS, DAYS, ValueRange.of(0, 23), "hour"),
/**
* The clock-hour-of-day.
*
* <p>This counts the hour within the day, from 1 to 24. This is the hour that would be observed
* on a 24-hour analog wall clock. This field has the same meaning for all calendar systems.
*
* <p>When parsing this field it behaves equivalent to the following: The value is validated from
* 1 to 24 in strict mode and from 0 to 24 in smart mode. In lenient mode the value is not
* validated. The field is converted to an {@code HOUR_OF_DAY} with the same value, unless the
* value is 24, in which case it is converted to 0.
*
* <p>See {@link #HOUR_OF_DAY} for the related field that counts hours from 0 to 23.
*/
CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1, 24)),
/**
* The am-pm-of-day.
* <p>
* This counts the AM/PM within the day, from 0 (AM) to 1 (PM).
* This field has the same meaning for all calendar systems.
* <p>
* When parsing this field it behaves equivalent to the following:
* The value is validated from 0 to 1 in strict and smart mode.
* In lenient mode the value is not validated. It is combined with
* {@code HOUR_OF_AMPM} to form {@code HOUR_OF_DAY} by multiplying
* the {AMPM_OF_DAY} value by 12.
*/
AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0, 1), "dayperiod"),
/**
* The day-of-week, such as Tuesday.
* <p>
* This represents the standard concept of the day of the week.
* In the default ISO calendar system, this has values from Monday (1) to Sunday (7).
* The {@link DayOfWeek} class can be used to interpret the result.
* <p>
* Most non-ISO calendar systems also define a seven day week that aligns with ISO.
* Those calendar systems must also use the same numbering system, from Monday (1) to
* Sunday (7), which allows {@code DayOfWeek} to be used.
* <p>
* Calendar systems that do not have a standard seven day week should implement this field
* if they have a similar concept of named or numbered days within a period similar
* to a week. It is recommended that the numbering starts from 1.
*/
DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1, 7), "weekday"),
/**
* The aligned day-of-week within a month.
* <p>
* This represents concept of the count of days within the period of a week
* where the weeks are aligned to the start of the month.
* This field is typically used with {@link #ALIGNED_WEEK_OF_MONTH}.
* <p>
* For example, in a calendar systems with a seven day week, the first aligned-week-of-month
* starts on day-of-month 1, the second aligned-week starts on day-of-month 8, and so on.
* Within each of these aligned-weeks, the days are numbered from 1 to 7 and returned
* as the value of this field.
* As such, day-of-month 1 to 7 will have aligned-day-of-week values from 1 to 7.
* And day-of-month 8 to 14 will repeat this with aligned-day-of-week values from 1 to 7.
* <p>
* Calendar systems that do not have a seven day week should typically implement this
* field in the same way, but using the alternate week length.
*/
ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7)),
/**
* The aligned day-of-week within a year.
* <p>
* This represents concept of the count of days within the period of a week
* where the weeks are aligned to the start of the year.
* This field is typically used with {@link #ALIGNED_WEEK_OF_YEAR}.
* <p>
* For example, in a calendar systems with a seven day week, the first aligned-week-of-year
* starts on day-of-year 1, the second aligned-week starts on day-of-year 8, and so on.
* Within each of these aligned-weeks, the days are numbered from 1 to 7 and returned
* as the value of this field.
* As such, day-of-year 1 to 7 will have aligned-day-of-week values from 1 to 7.
* And day-of-year 8 to 14 will repeat this with aligned-day-of-week values from 1 to 7.
* <p>
* Calendar systems that do not have a seven day week should typically implement this
* field in the same way, but using the alternate week length.
*/
ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7)),
/**
* The day-of-month.
* <p>
* This represents the concept of the day within the month.
* In the default ISO calendar system, this has values from 1 to 31 in most months.
* April, June, September, November have days from 1 to 30, while February has days
* from 1 to 28, or 29 in a leap year.
* <p>
* Non-ISO calendar systems should implement this field using the most recognized
* day-of-month values for users of the calendar system.
* Normally, this is a count of days from 1 to the length of the month.
*/
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),
/**
* The day-of-year.
* <p>
* This represents the concept of the day within the year.
* In the default ISO calendar system, this has values from 1 to 365 in standard
* years and 1 to 366 in leap years.
* <p>
* Non-ISO calendar systems should implement this field using the most recognized
* day-of-year values for users of the calendar system.
* Normally, this is a count of days from 1 to the length of the year.
* <p>
* Note that a non-ISO calendar system may have year numbering system that changes
* at a different point to the natural reset in the month numbering. An example
* of this is the Japanese calendar system where a change of era, which resets
* the year number to 1, can happen on any date. The era and year reset also cause
* the day-of-year to be reset to 1, but not the month-of-year or day-of-month.
*/
DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366)),
/**
* The epoch-day, based on the Java epoch of 1970-01-01 (ISO).
*
* <p>This field is the sequential count of days where 1970-01-01 (ISO) is zero. Note that this
* uses the <i>local</i> time-line, ignoring offset and time-zone.
*
* <p>This field is strictly defined to have the same meaning in all calendar systems. This is
* necessary to ensure interoperation between calendars.
*
* <p>Range of EpochDay is between (LocalDate.MIN.toEpochDay(), LocalDate.MAX.toEpochDay()) both
* inclusive.
*/
EPOCH_DAY("EpochDay", DAYS, FOREVER, ValueRange.of(-365243219162L, 365241780471L)),
/**
* The aligned week within a month.
* <p>
* This represents concept of the count of weeks within the period of a month
* where the weeks are aligned to the start of the month.
* This field is typically used with {@link #ALIGNED_DAY_OF_WEEK_IN_MONTH}.
* <p>
* For example, in a calendar systems with a seven day week, the first aligned-week-of-month
* starts on day-of-month 1, the second aligned-week starts on day-of-month 8, and so on.
* Thus, day-of-month values 1 to 7 are in aligned-week 1, while day-of-month values
* 8 to 14 are in aligned-week 2, and so on.
* <p>
* Calendar systems that do not have a seven day week should typically implement this
* field in the same way, but using the alternate week length.
*/
ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5)),
/**
* The aligned week within a year.
* <p>
* This represents concept of the count of weeks within the period of a year
* where the weeks are aligned to the start of the year.
* This field is typically used with {@link #ALIGNED_DAY_OF_WEEK_IN_YEAR}.
* <p>
* For example, in a calendar systems with a seven day week, the first aligned-week-of-year
* starts on day-of-year 1, the second aligned-week starts on day-of-year 8, and so on.
* Thus, day-of-year values 1 to 7 are in aligned-week 1, while day-of-year values
* 8 to 14 are in aligned-week 2, and so on.
* <p>
* Calendar systems that do not have a seven day week should typically implement this
* field in the same way, but using the alternate week length.
*/
ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53)),
/**
* The month-of-year, such as March.
* <p>
* This represents the concept of the month within the year.
* In the default ISO calendar system, this has values from January (1) to December (12).
* <p>
* Non-ISO calendar systems should implement this field using the most recognized
* month-of-year values for users of the calendar system.
* Normally, this is a count of months starting from 1.
*/
MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1, 12), "month"),
/**
* The proleptic-month based, counting months sequentially from year 0.
*
* <p>This field is the sequential count of months where the first month in proleptic-year zero
* has the value zero. Later months have increasingly larger values. Earlier months have
* increasingly small values. There are no gaps or breaks in the sequence of months. Note that
* this uses the <i>local</i> time-line, ignoring offset and time-zone.
*
* <p>In the default ISO calendar system, June 2012 would have the value {@code (2012 * 12 + 6 -
* 1)}. This field is primarily for internal use.
*
* <p>Non-ISO calendar systems must implement this field as per the definition above. It is just a
* simple zero-based count of elapsed months from the start of proleptic-year 0. All calendar
* systems with a full proleptic-year definition will have a year zero. If the calendar system has
* a minimum year that excludes year zero, then one must be extrapolated in order for this method
* to be defined.
*/
PROLEPTIC_MONTH(
"ProlepticMonth",
MONTHS,
FOREVER,
ValueRange.of(Year.MIN_VALUE * 12L, Year.MAX_VALUE * 12L + 11)),
/**
* The year within the era.
* <p>
* This represents the concept of the year within the era.
* This field is typically used with {@link #ERA}.
* <p>
* The standard mental model for a date is based on three concepts - year, month and day.
* These map onto the {@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields.
* Note that there is no reference to eras.
* The full model for a date requires four concepts - era, year, month and day. These map onto
* the {@code ERA}, {@code YEAR_OF_ERA}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields.
* Whether this field or {@code YEAR} is used depends on which mental model is being used.
* See {@link ChronoLocalDate} for more discussion on this topic.
* <p>
* In the default ISO calendar system, there are two eras defined, 'BCE' and 'CE'.
* The era 'CE' is the one currently in use and year-of-era runs from 1 to the maximum value.
* The era 'BCE' is the previous era, and the year-of-era runs backwards.
* <p>
* For example, subtracting a year each time yield the following:<br>
* - year-proleptic 2 = 'CE' year-of-era 2<br>
* - year-proleptic 1 = 'CE' year-of-era 1<br>
* - year-proleptic 0 = 'BCE' year-of-era 1<br>
* - year-proleptic -1 = 'BCE' year-of-era 2<br>
* <p>
* Note that the ISO-8601 standard does not actually define eras.
* Note also that the ISO eras do not align with the well-known AD/BC eras due to the
* change between the Julian and Gregorian calendar systems.
* <p>
* Non-ISO calendar systems should implement this field using the most recognized
* year-of-era value for users of the calendar system.
* Since most calendar systems have only two eras, the year-of-era numbering approach
* will typically be the same as that used by the ISO calendar system.
* The year-of-era value should typically always be positive, however this is not required.
*/
YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, ValueRange.of(1, Year.MAX_VALUE, Year.MAX_VALUE + 1)),
/**
* The proleptic year, such as 2012.
* <p>
* This represents the concept of the year, counting sequentially and using negative numbers.
* The proleptic year is not interpreted in terms of the era.
* See {@link #YEAR_OF_ERA} for an example showing the mapping from proleptic year to year-of-era.
* <p>
* The standard mental model for a date is based on three concepts - year, month and day.
* These map onto the {@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields.
* Note that there is no reference to eras.
* The full model for a date requires four concepts - era, year, month and day. These map onto
* the {@code ERA}, {@code YEAR_OF_ERA}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} fields.
* Whether this field or {@code YEAR_OF_ERA} is used depends on which mental model is being used.
* See {@link ChronoLocalDate} for more discussion on this topic.
* <p>
* Non-ISO calendar systems should implement this field as follows.
* If the calendar system has only two eras, before and after a fixed date, then the
* proleptic-year value must be the same as the year-of-era value for the later era,
* and increasingly negative for the earlier era.
* If the calendar system has more than two eras, then the proleptic-year value may be
* defined with any appropriate value, although defining it to be the same as ISO may be
* the best option.
*/
YEAR("Year", YEARS, FOREVER, ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), "year"),
/**
* The era.
* <p>
* This represents the concept of the era, which is the largest division of the time-line.
* This field is typically used with {@link #YEAR_OF_ERA}.
* <p>
* In the default ISO calendar system, there are two eras defined, 'BCE' and 'CE'.
* The era 'CE' is the one currently in use and year-of-era runs from 1 to the maximum value.
* The era 'BCE' is the previous era, and the year-of-era runs backwards.
* See {@link #YEAR_OF_ERA} for a full example.
* <p>
* Non-ISO calendar systems should implement this field to define eras.
* The value of the era that was active on 1970-01-01 (ISO) must be assigned the value 1.
* Earlier eras must have sequentially smaller values.
* Later eras must have sequentially larger values,
*/
ERA("Era", ERAS, FOREVER, ValueRange.of(0, 1), "era"),
/**
* The instant epoch-seconds.
*
* <p>This represents the concept of the sequential count of seconds where 1970-01-01T00:00Z (ISO)
* is zero. This field may be used with {@link #NANO_OF_SECOND} to represent the fraction of the
* second.
*
* <p>An {@link Instant} represents an instantaneous point on the time-line. On their own, an
* instant has insufficient information to allow a local date-time to be obtained. Only when
* paired with an offset or time-zone can the local date or time be calculated.
*
* <p>This field is strictly defined to have the same meaning in all calendar systems. This is
* necessary to ensure interoperation between calendars.
*/
INSTANT_SECONDS(
"InstantSeconds", SECONDS, FOREVER, ValueRange.of(Long.MIN_VALUE, Long.MAX_VALUE)),
/**
* The offset from UTC/Greenwich.
* <p>
* This represents the concept of the offset in seconds of local time from UTC/Greenwich.
* <p>
* A {@link ZoneOffset} represents the period of time that local time differs from UTC/Greenwich.
* This is usually a fixed number of hours and minutes.
* It is equivalent to the {@link ZoneOffset#getTotalSeconds() total amount} of the offset in seconds.
* For example, during the winter Paris has an offset of {@code +01:00}, which is 3600 seconds.
* <p>
* This field is strictly defined to have the same meaning in all calendar systems.
* This is necessary to ensure interoperation between calendars.
*/
OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, ValueRange.of(-18 * 3600, 18 * 3600));
private final String name;
private final TemporalUnit baseUnit;
private final TemporalUnit rangeUnit;
private final ValueRange range;
private final String displayNameKey;
private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = null;
}
private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
ValueRange range, String displayNameKey) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = displayNameKey;
}
@Override
public String getDisplayName(Locale locale) {
Objects.requireNonNull(locale, "locale");
if (displayNameKey == null) {
return name;
}
// BEGIN Android-changed: use ICU names.
/*
LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased()
.getLocaleResources(
CalendarDataUtility
.findRegionOverride(locale));
ResourceBundle rb = lr.getJavaTimeFormatData();
String key = "field." + displayNameKey;
return rb.containsKey(key) ? rb.getString(key) : name;
*/
DateTimePatternGenerator generator =
DateTimePatternGenerator.getInstance(ULocale.forLocale(locale));
String icuName = generator.getAppendItemName(getIcuFieldNumber(this));
return icuName != null && !icuName.isEmpty() ? icuName : name;
}
/**
* @return the field id according to {@link DateTimePatternGenerator} for the field.
*/
private static int getIcuFieldNumber(ChronoField field) {
switch (field) {
case SECOND_OF_MINUTE:
return DateTimePatternGenerator.SECOND;
case MINUTE_OF_HOUR:
return DateTimePatternGenerator.MINUTE;
case HOUR_OF_DAY:
return DateTimePatternGenerator.HOUR;
case AMPM_OF_DAY:
return DateTimePatternGenerator.DAYPERIOD;
case DAY_OF_WEEK:
return DateTimePatternGenerator.WEEKDAY;
case DAY_OF_MONTH:
return DateTimePatternGenerator.DAY;
case MONTH_OF_YEAR:
return DateTimePatternGenerator.MONTH;
case YEAR:
return DateTimePatternGenerator.YEAR;
case ERA:
return DateTimePatternGenerator.ERA;
default:
throw new IllegalArgumentException("Unexpected ChronoField " + field.name());
}
// END Android-changed: use ICU names.
}
@Override
public TemporalUnit getBaseUnit() {
return baseUnit;
}
@Override
public TemporalUnit getRangeUnit() {
return rangeUnit;
}
/**
* Gets the range of valid values for the field.
* <p>
* All fields can be expressed as a {@code long} integer.
* This method returns an object that describes the valid range for that value.
* <p>
* This method returns the range of the field in the ISO-8601 calendar system.
* This range may be incorrect for other calendar systems.
* Use {@link Chronology#range(ChronoField)} to access the correct range
* for a different calendar system.
* <p>
* Note that the result only describes the minimum and maximum valid values
* and it is important not to read too much into them. For example, there
* could be values within the range that are invalid for the field.
*
* @return the range of valid values for the field, not null
*/
@Override
public ValueRange range() {
return range;
}
//-----------------------------------------------------------------------
/**
* Checks if this field represents a component of a date.
* <p>
* Fields from day-of-week to era are date-based.
*
* @return true if it is a component of a date
*/
@Override
public boolean isDateBased() {
return ordinal() >= DAY_OF_WEEK.ordinal() && ordinal() <= ERA.ordinal();
}
/**
* Checks if this field represents a component of a time.
* <p>
* Fields from nano-of-second to am-pm-of-day are time-based.
*
* @return true if it is a component of a time
*/
@Override
public boolean isTimeBased() {
return ordinal() < DAY_OF_WEEK.ordinal();
}
//-----------------------------------------------------------------------
/**
* Checks that the specified value is valid for this field.
* <p>
* This validates that the value is within the outer range of valid values
* returned by {@link #range()}.
* <p>
* This method checks against the range of the field in the ISO-8601 calendar system.
* This range may be incorrect for other calendar systems.
* Use {@link Chronology#range(ChronoField)} to access the correct range
* for a different calendar system.
*
* @param value the value to check
* @return the value that was passed in
*/
public long checkValidValue(long value) {
return range().checkValidValue(value, this);
}
/**
* Checks that the specified value is valid and fits in an {@code int}.
* <p>
* This validates that the value is within the outer range of valid values
* returned by {@link #range()}.
* It also checks that all valid values are within the bounds of an {@code int}.
* <p>
* This method checks against the range of the field in the ISO-8601 calendar system.
* This range may be incorrect for other calendar systems.
* Use {@link Chronology#range(ChronoField)} to access the correct range
* for a different calendar system.
*
* @param value the value to check
* @return the value that was passed in
*/
public int checkValidIntValue(long value) {
return range().checkValidIntValue(value, this);
}
//-----------------------------------------------------------------------
@Override
public boolean isSupportedBy(TemporalAccessor temporal) {
return temporal.isSupported(this);
}
@Override
public ValueRange rangeRefinedBy(TemporalAccessor temporal) {
return temporal.range(this);
}
@Override
public long getFrom(TemporalAccessor temporal) {
return temporal.getLong(this);
}
@SuppressWarnings("unchecked")
@Override
public <R extends Temporal> R adjustInto(R temporal, long newValue) {
return (R) temporal.with(this, newValue);
}
//-----------------------------------------------------------------------
@Override
public String toString() {
return name;
}
}
|
googleapis/google-cloud-java | 37,968 | java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/ListGroupMembersResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/group_service.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* The `ListGroupMembers` response.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.ListGroupMembersResponse}
*/
public final class ListGroupMembersResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.ListGroupMembersResponse)
ListGroupMembersResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListGroupMembersResponse.newBuilder() to construct.
private ListGroupMembersResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListGroupMembersResponse() {
members_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListGroupMembersResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.GroupServiceProto
.internal_static_google_monitoring_v3_ListGroupMembersResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.GroupServiceProto
.internal_static_google_monitoring_v3_ListGroupMembersResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.ListGroupMembersResponse.class,
com.google.monitoring.v3.ListGroupMembersResponse.Builder.class);
}
public static final int MEMBERS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.api.MonitoredResource> members_;
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.api.MonitoredResource> getMembersList() {
return members_;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.api.MonitoredResourceOrBuilder>
getMembersOrBuilderList() {
return members_;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
@java.lang.Override
public int getMembersCount() {
return members_.size();
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
@java.lang.Override
public com.google.api.MonitoredResource getMembers(int index) {
return members_.get(index);
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
@java.lang.Override
public com.google.api.MonitoredResourceOrBuilder getMembersOrBuilder(int index) {
return members_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </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;
}
}
public static final int TOTAL_SIZE_FIELD_NUMBER = 3;
private int totalSize_ = 0;
/**
*
*
* <pre>
* The total number of elements matching this request.
* </pre>
*
* <code>int32 total_size = 3;</code>
*
* @return The totalSize.
*/
@java.lang.Override
public int getTotalSize() {
return totalSize_;
}
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 < members_.size(); i++) {
output.writeMessage(1, members_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
if (totalSize_ != 0) {
output.writeInt32(3, totalSize_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < members_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, members_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
if (totalSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, totalSize_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.ListGroupMembersResponse)) {
return super.equals(obj);
}
com.google.monitoring.v3.ListGroupMembersResponse other =
(com.google.monitoring.v3.ListGroupMembersResponse) obj;
if (!getMembersList().equals(other.getMembersList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (getTotalSize() != other.getTotalSize()) 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 (getMembersCount() > 0) {
hash = (37 * hash) + MEMBERS_FIELD_NUMBER;
hash = (53 * hash) + getMembersList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (37 * hash) + TOTAL_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getTotalSize();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListGroupMembersResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.ListGroupMembersResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The `ListGroupMembers` response.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.ListGroupMembersResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.ListGroupMembersResponse)
com.google.monitoring.v3.ListGroupMembersResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.GroupServiceProto
.internal_static_google_monitoring_v3_ListGroupMembersResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.GroupServiceProto
.internal_static_google_monitoring_v3_ListGroupMembersResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.ListGroupMembersResponse.class,
com.google.monitoring.v3.ListGroupMembersResponse.Builder.class);
}
// Construct using com.google.monitoring.v3.ListGroupMembersResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (membersBuilder_ == null) {
members_ = java.util.Collections.emptyList();
} else {
members_ = null;
membersBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
totalSize_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.GroupServiceProto
.internal_static_google_monitoring_v3_ListGroupMembersResponse_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.ListGroupMembersResponse getDefaultInstanceForType() {
return com.google.monitoring.v3.ListGroupMembersResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.ListGroupMembersResponse build() {
com.google.monitoring.v3.ListGroupMembersResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.ListGroupMembersResponse buildPartial() {
com.google.monitoring.v3.ListGroupMembersResponse result =
new com.google.monitoring.v3.ListGroupMembersResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.monitoring.v3.ListGroupMembersResponse result) {
if (membersBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
members_ = java.util.Collections.unmodifiableList(members_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.members_ = members_;
} else {
result.members_ = membersBuilder_.build();
}
}
private void buildPartial0(com.google.monitoring.v3.ListGroupMembersResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.totalSize_ = totalSize_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.ListGroupMembersResponse) {
return mergeFrom((com.google.monitoring.v3.ListGroupMembersResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.ListGroupMembersResponse other) {
if (other == com.google.monitoring.v3.ListGroupMembersResponse.getDefaultInstance())
return this;
if (membersBuilder_ == null) {
if (!other.members_.isEmpty()) {
if (members_.isEmpty()) {
members_ = other.members_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMembersIsMutable();
members_.addAll(other.members_);
}
onChanged();
}
} else {
if (!other.members_.isEmpty()) {
if (membersBuilder_.isEmpty()) {
membersBuilder_.dispose();
membersBuilder_ = null;
members_ = other.members_;
bitField0_ = (bitField0_ & ~0x00000001);
membersBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMembersFieldBuilder()
: null;
} else {
membersBuilder_.addAllMessages(other.members_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getTotalSize() != 0) {
setTotalSize(other.getTotalSize());
}
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.MonitoredResource m =
input.readMessage(com.google.api.MonitoredResource.parser(), extensionRegistry);
if (membersBuilder_ == null) {
ensureMembersIsMutable();
members_.add(m);
} else {
membersBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
totalSize_ = input.readInt32();
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.util.List<com.google.api.MonitoredResource> members_ =
java.util.Collections.emptyList();
private void ensureMembersIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
members_ = new java.util.ArrayList<com.google.api.MonitoredResource>(members_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.MonitoredResource,
com.google.api.MonitoredResource.Builder,
com.google.api.MonitoredResourceOrBuilder>
membersBuilder_;
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public java.util.List<com.google.api.MonitoredResource> getMembersList() {
if (membersBuilder_ == null) {
return java.util.Collections.unmodifiableList(members_);
} else {
return membersBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public int getMembersCount() {
if (membersBuilder_ == null) {
return members_.size();
} else {
return membersBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public com.google.api.MonitoredResource getMembers(int index) {
if (membersBuilder_ == null) {
return members_.get(index);
} else {
return membersBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder setMembers(int index, com.google.api.MonitoredResource value) {
if (membersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembersIsMutable();
members_.set(index, value);
onChanged();
} else {
membersBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder setMembers(int index, com.google.api.MonitoredResource.Builder builderForValue) {
if (membersBuilder_ == null) {
ensureMembersIsMutable();
members_.set(index, builderForValue.build());
onChanged();
} else {
membersBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder addMembers(com.google.api.MonitoredResource value) {
if (membersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembersIsMutable();
members_.add(value);
onChanged();
} else {
membersBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder addMembers(int index, com.google.api.MonitoredResource value) {
if (membersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMembersIsMutable();
members_.add(index, value);
onChanged();
} else {
membersBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder addMembers(com.google.api.MonitoredResource.Builder builderForValue) {
if (membersBuilder_ == null) {
ensureMembersIsMutable();
members_.add(builderForValue.build());
onChanged();
} else {
membersBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder addMembers(int index, com.google.api.MonitoredResource.Builder builderForValue) {
if (membersBuilder_ == null) {
ensureMembersIsMutable();
members_.add(index, builderForValue.build());
onChanged();
} else {
membersBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder addAllMembers(
java.lang.Iterable<? extends com.google.api.MonitoredResource> values) {
if (membersBuilder_ == null) {
ensureMembersIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, members_);
onChanged();
} else {
membersBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder clearMembers() {
if (membersBuilder_ == null) {
members_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
membersBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public Builder removeMembers(int index) {
if (membersBuilder_ == null) {
ensureMembersIsMutable();
members_.remove(index);
onChanged();
} else {
membersBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public com.google.api.MonitoredResource.Builder getMembersBuilder(int index) {
return getMembersFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public com.google.api.MonitoredResourceOrBuilder getMembersOrBuilder(int index) {
if (membersBuilder_ == null) {
return members_.get(index);
} else {
return membersBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public java.util.List<? extends com.google.api.MonitoredResourceOrBuilder>
getMembersOrBuilderList() {
if (membersBuilder_ != null) {
return membersBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(members_);
}
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public com.google.api.MonitoredResource.Builder addMembersBuilder() {
return getMembersFieldBuilder()
.addBuilder(com.google.api.MonitoredResource.getDefaultInstance());
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public com.google.api.MonitoredResource.Builder addMembersBuilder(int index) {
return getMembersFieldBuilder()
.addBuilder(index, com.google.api.MonitoredResource.getDefaultInstance());
}
/**
*
*
* <pre>
* A set of monitored resources in the group.
* </pre>
*
* <code>repeated .google.api.MonitoredResource members = 1;</code>
*/
public java.util.List<com.google.api.MonitoredResource.Builder> getMembersBuilderList() {
return getMembersFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.MonitoredResource,
com.google.api.MonitoredResource.Builder,
com.google.api.MonitoredResourceOrBuilder>
getMembersFieldBuilder() {
if (membersBuilder_ == null) {
membersBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.MonitoredResource,
com.google.api.MonitoredResource.Builder,
com.google.api.MonitoredResourceOrBuilder>(
members_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
members_ = null;
}
return membersBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* If there are more results than have been returned, then this field is
* set to a non-empty value. To see the additional results, use that value as
* `page_token` in the next call to this method.
* </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;
}
private int totalSize_;
/**
*
*
* <pre>
* The total number of elements matching this request.
* </pre>
*
* <code>int32 total_size = 3;</code>
*
* @return The totalSize.
*/
@java.lang.Override
public int getTotalSize() {
return totalSize_;
}
/**
*
*
* <pre>
* The total number of elements matching this request.
* </pre>
*
* <code>int32 total_size = 3;</code>
*
* @param value The totalSize to set.
* @return This builder for chaining.
*/
public Builder setTotalSize(int value) {
totalSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The total number of elements matching this request.
* </pre>
*
* <code>int32 total_size = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearTotalSize() {
bitField0_ = (bitField0_ & ~0x00000004);
totalSize_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.ListGroupMembersResponse)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.ListGroupMembersResponse)
private static final com.google.monitoring.v3.ListGroupMembersResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.ListGroupMembersResponse();
}
public static com.google.monitoring.v3.ListGroupMembersResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListGroupMembersResponse> PARSER =
new com.google.protobuf.AbstractParser<ListGroupMembersResponse>() {
@java.lang.Override
public ListGroupMembersResponse 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<ListGroupMembersResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListGroupMembersResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.ListGroupMembersResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,098 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/UpdatePersistentResourceRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/persistent_resource_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Request message for UpdatePersistentResource method.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.UpdatePersistentResourceRequest}
*/
public final class UpdatePersistentResourceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.UpdatePersistentResourceRequest)
UpdatePersistentResourceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdatePersistentResourceRequest.newBuilder() to construct.
private UpdatePersistentResourceRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdatePersistentResourceRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdatePersistentResourceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_UpdatePersistentResourceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_UpdatePersistentResourceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.class,
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.Builder.class);
}
private int bitField0_;
public static final int PERSISTENT_RESOURCE_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.PersistentResource persistentResource_;
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the persistentResource field is set.
*/
@java.lang.Override
public boolean hasPersistentResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The persistentResource.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PersistentResource getPersistentResource() {
return persistentResource_ == null
? com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance()
: persistentResource_;
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder
getPersistentResourceOrBuilder() {
return persistentResource_ == null
? com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance()
: persistentResource_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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, getPersistentResource());
}
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, getPersistentResource());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest other =
(com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest) obj;
if (hasPersistentResource() != other.hasPersistentResource()) return false;
if (hasPersistentResource()) {
if (!getPersistentResource().equals(other.getPersistentResource())) 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 (hasPersistentResource()) {
hash = (37 * hash) + PERSISTENT_RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getPersistentResource().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest 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 UpdatePersistentResource method.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.UpdatePersistentResourceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.UpdatePersistentResourceRequest)
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_UpdatePersistentResourceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_UpdatePersistentResourceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.class,
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPersistentResourceFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
persistentResource_ = null;
if (persistentResourceBuilder_ != null) {
persistentResourceBuilder_.dispose();
persistentResourceBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.PersistentResourceServiceProto
.internal_static_google_cloud_aiplatform_v1_UpdatePersistentResourceRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest build() {
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest buildPartial() {
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest result =
new com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.persistentResource_ =
persistentResourceBuilder_ == null
? persistentResource_
: persistentResourceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest other) {
if (other
== com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest.getDefaultInstance())
return this;
if (other.hasPersistentResource()) {
mergePersistentResource(other.getPersistentResource());
}
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(
getPersistentResourceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.aiplatform.v1.PersistentResource persistentResource_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
persistentResourceBuilder_;
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the persistentResource field is set.
*/
public boolean hasPersistentResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The persistentResource.
*/
public com.google.cloud.aiplatform.v1.PersistentResource getPersistentResource() {
if (persistentResourceBuilder_ == null) {
return persistentResource_ == null
? com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance()
: persistentResource_;
} else {
return persistentResourceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setPersistentResource(com.google.cloud.aiplatform.v1.PersistentResource value) {
if (persistentResourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
persistentResource_ = value;
} else {
persistentResourceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setPersistentResource(
com.google.cloud.aiplatform.v1.PersistentResource.Builder builderForValue) {
if (persistentResourceBuilder_ == null) {
persistentResource_ = builderForValue.build();
} else {
persistentResourceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergePersistentResource(
com.google.cloud.aiplatform.v1.PersistentResource value) {
if (persistentResourceBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& persistentResource_ != null
&& persistentResource_
!= com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance()) {
getPersistentResourceBuilder().mergeFrom(value);
} else {
persistentResource_ = value;
}
} else {
persistentResourceBuilder_.mergeFrom(value);
}
if (persistentResource_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearPersistentResource() {
bitField0_ = (bitField0_ & ~0x00000001);
persistentResource_ = null;
if (persistentResourceBuilder_ != null) {
persistentResourceBuilder_.dispose();
persistentResourceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResource.Builder
getPersistentResourceBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getPersistentResourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder
getPersistentResourceOrBuilder() {
if (persistentResourceBuilder_ != null) {
return persistentResourceBuilder_.getMessageOrBuilder();
} else {
return persistentResource_ == null
? com.google.cloud.aiplatform.v1.PersistentResource.getDefaultInstance()
: persistentResource_;
}
}
/**
*
*
* <pre>
* Required. The PersistentResource to update.
*
* The PersistentResource's `name` field is used to identify the
* PersistentResource to update. Format:
* `projects/{project}/locations/{location}/persistentResources/{persistent_resource}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PersistentResource persistent_resource = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>
getPersistentResourceFieldBuilder() {
if (persistentResourceBuilder_ == null) {
persistentResourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PersistentResource,
com.google.cloud.aiplatform.v1.PersistentResource.Builder,
com.google.cloud.aiplatform.v1.PersistentResourceOrBuilder>(
getPersistentResource(), getParentForChildren(), isClean());
persistentResource_ = null;
}
return persistentResourceBuilder_;
}
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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </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. Specify the fields to be overwritten in the PersistentResource by
* the update method.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.UpdatePersistentResourceRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.UpdatePersistentResourceRequest)
private static final com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest();
}
public static com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdatePersistentResourceRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdatePersistentResourceRequest>() {
@java.lang.Override
public UpdatePersistentResourceRequest 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<UpdatePersistentResourceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdatePersistentResourceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.UpdatePersistentResourceRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,032 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/ListWebhooksResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3/webhook.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3;
/**
*
*
* <pre>
* The response message for
* [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ListWebhooksResponse}
*/
public final class ListWebhooksResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3.ListWebhooksResponse)
ListWebhooksResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListWebhooksResponse.newBuilder() to construct.
private ListWebhooksResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListWebhooksResponse() {
webhooks_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListWebhooksResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.WebhookProto
.internal_static_google_cloud_dialogflow_cx_v3_ListWebhooksResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.WebhookProto
.internal_static_google_cloud_dialogflow_cx_v3_ListWebhooksResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.class,
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.Builder.class);
}
public static final int WEBHOOKS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.dialogflow.cx.v3.Webhook> webhooks_;
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.cx.v3.Webhook> getWebhooksList() {
return webhooks_;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder>
getWebhooksOrBuilderList() {
return webhooks_;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
@java.lang.Override
public int getWebhooksCount() {
return webhooks_.size();
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.Webhook getWebhooks(int index) {
return webhooks_.get(index);
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder getWebhooksOrBuilder(int index) {
return webhooks_.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 < webhooks_.size(); i++) {
output.writeMessage(1, webhooks_.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 < webhooks_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, webhooks_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse other =
(com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse) obj;
if (!getWebhooksList().equals(other.getWebhooksList())) 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 (getWebhooksCount() > 0) {
hash = (37 * hash) + WEBHOOKS_FIELD_NUMBER;
hash = (53 * hash) + getWebhooksList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for
* [Webhooks.ListWebhooks][google.cloud.dialogflow.cx.v3.Webhooks.ListWebhooks].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3.ListWebhooksResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3.ListWebhooksResponse)
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3.WebhookProto
.internal_static_google_cloud_dialogflow_cx_v3_ListWebhooksResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3.WebhookProto
.internal_static_google_cloud_dialogflow_cx_v3_ListWebhooksResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.class,
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.Builder.class);
}
// Construct using com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (webhooksBuilder_ == null) {
webhooks_ = java.util.Collections.emptyList();
} else {
webhooks_ = null;
webhooksBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3.WebhookProto
.internal_static_google_cloud_dialogflow_cx_v3_ListWebhooksResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse build() {
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse buildPartial() {
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse result =
new com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse result) {
if (webhooksBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
webhooks_ = java.util.Collections.unmodifiableList(webhooks_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.webhooks_ = webhooks_;
} else {
result.webhooks_ = webhooksBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse) {
return mergeFrom((com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse other) {
if (other == com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse.getDefaultInstance())
return this;
if (webhooksBuilder_ == null) {
if (!other.webhooks_.isEmpty()) {
if (webhooks_.isEmpty()) {
webhooks_ = other.webhooks_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureWebhooksIsMutable();
webhooks_.addAll(other.webhooks_);
}
onChanged();
}
} else {
if (!other.webhooks_.isEmpty()) {
if (webhooksBuilder_.isEmpty()) {
webhooksBuilder_.dispose();
webhooksBuilder_ = null;
webhooks_ = other.webhooks_;
bitField0_ = (bitField0_ & ~0x00000001);
webhooksBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getWebhooksFieldBuilder()
: null;
} else {
webhooksBuilder_.addAllMessages(other.webhooks_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.dialogflow.cx.v3.Webhook m =
input.readMessage(
com.google.cloud.dialogflow.cx.v3.Webhook.parser(), extensionRegistry);
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
webhooks_.add(m);
} else {
webhooksBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.cx.v3.Webhook> webhooks_ =
java.util.Collections.emptyList();
private void ensureWebhooksIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
webhooks_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3.Webhook>(webhooks_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Webhook,
com.google.cloud.dialogflow.cx.v3.Webhook.Builder,
com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder>
webhooksBuilder_;
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3.Webhook> getWebhooksList() {
if (webhooksBuilder_ == null) {
return java.util.Collections.unmodifiableList(webhooks_);
} else {
return webhooksBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public int getWebhooksCount() {
if (webhooksBuilder_ == null) {
return webhooks_.size();
} else {
return webhooksBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Webhook getWebhooks(int index) {
if (webhooksBuilder_ == null) {
return webhooks_.get(index);
} else {
return webhooksBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder setWebhooks(int index, com.google.cloud.dialogflow.cx.v3.Webhook value) {
if (webhooksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWebhooksIsMutable();
webhooks_.set(index, value);
onChanged();
} else {
webhooksBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder setWebhooks(
int index, com.google.cloud.dialogflow.cx.v3.Webhook.Builder builderForValue) {
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
webhooks_.set(index, builderForValue.build());
onChanged();
} else {
webhooksBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder addWebhooks(com.google.cloud.dialogflow.cx.v3.Webhook value) {
if (webhooksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWebhooksIsMutable();
webhooks_.add(value);
onChanged();
} else {
webhooksBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder addWebhooks(int index, com.google.cloud.dialogflow.cx.v3.Webhook value) {
if (webhooksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWebhooksIsMutable();
webhooks_.add(index, value);
onChanged();
} else {
webhooksBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder addWebhooks(com.google.cloud.dialogflow.cx.v3.Webhook.Builder builderForValue) {
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
webhooks_.add(builderForValue.build());
onChanged();
} else {
webhooksBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder addWebhooks(
int index, com.google.cloud.dialogflow.cx.v3.Webhook.Builder builderForValue) {
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
webhooks_.add(index, builderForValue.build());
onChanged();
} else {
webhooksBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder addAllWebhooks(
java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3.Webhook> values) {
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, webhooks_);
onChanged();
} else {
webhooksBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder clearWebhooks() {
if (webhooksBuilder_ == null) {
webhooks_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
webhooksBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public Builder removeWebhooks(int index) {
if (webhooksBuilder_ == null) {
ensureWebhooksIsMutable();
webhooks_.remove(index);
onChanged();
} else {
webhooksBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Webhook.Builder getWebhooksBuilder(int index) {
return getWebhooksFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder getWebhooksOrBuilder(int index) {
if (webhooksBuilder_ == null) {
return webhooks_.get(index);
} else {
return webhooksBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder>
getWebhooksOrBuilderList() {
if (webhooksBuilder_ != null) {
return webhooksBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(webhooks_);
}
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Webhook.Builder addWebhooksBuilder() {
return getWebhooksFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.cx.v3.Webhook.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public com.google.cloud.dialogflow.cx.v3.Webhook.Builder addWebhooksBuilder(int index) {
return getWebhooksFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.cx.v3.Webhook.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of webhooks. There will be a maximum number of items returned
* based on the page_size field in the request.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.cx.v3.Webhook webhooks = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.cx.v3.Webhook.Builder>
getWebhooksBuilderList() {
return getWebhooksFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Webhook,
com.google.cloud.dialogflow.cx.v3.Webhook.Builder,
com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder>
getWebhooksFieldBuilder() {
if (webhooksBuilder_ == null) {
webhooksBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.cx.v3.Webhook,
com.google.cloud.dialogflow.cx.v3.Webhook.Builder,
com.google.cloud.dialogflow.cx.v3.WebhookOrBuilder>(
webhooks_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
webhooks_ = null;
}
return webhooksBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.cx.v3.ListWebhooksResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3.ListWebhooksResponse)
private static final com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse();
}
public static com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListWebhooksResponse> PARSER =
new com.google.protobuf.AbstractParser<ListWebhooksResponse>() {
@java.lang.Override
public ListWebhooksResponse 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<ListWebhooksResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListWebhooksResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3.ListWebhooksResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ozone | 38,292 | hadoop-ozone/ozone-manager/src/test/java/org/apache/hadoop/ozone/om/request/key/TestOMKeyCommitRequest.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.om.request.key;
import static org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.KEY_NOT_FOUND;
import static org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.Status.OK;
import static org.assertj.core.api.Assertions.assertThat;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when;
import jakarta.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.hadoop.hdds.client.RatisReplicationConfig;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.utils.db.BatchOperation;
import org.apache.hadoop.hdds.utils.db.Table;
import org.apache.hadoop.ozone.OmUtils;
import org.apache.hadoop.ozone.OzoneAcl;
import org.apache.hadoop.ozone.OzoneConfigKeys;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.om.exceptions.OMException;
import org.apache.hadoop.ozone.om.helpers.BucketLayout;
import org.apache.hadoop.ozone.om.helpers.OmBucketInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfoGroup;
import org.apache.hadoop.ozone.om.helpers.OzoneFSUtils;
import org.apache.hadoop.ozone.om.helpers.RepeatedOmKeyInfo;
import org.apache.hadoop.ozone.om.request.OMRequestTestUtils;
import org.apache.hadoop.ozone.om.response.OMClientResponse;
import org.apache.hadoop.ozone.om.response.key.OMKeyCommitResponse;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.CommitKeyRequest;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyArgs;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyLocation;
import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMRequest;
import org.apache.hadoop.util.Time;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* Class tests OMKeyCommitRequest class.
*/
public class TestOMKeyCommitRequest extends TestOMKeyRequest {
private static final int DEFAULT_COMMIT_BLOCK_SIZE = 5;
private String parentDir;
@Test
public void testPreExecute() throws Exception {
doPreExecute(createCommitKeyRequest());
}
@Test
public void testValidateAndUpdateCacheWithUnknownBlockId() throws Exception {
OMRequest modifiedOmRequest =
doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
// Append 3 blocks locations.
List<OmKeyLocationInfo> allocatedLocationList = getKeyLocation(3)
.stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, omKeyCommitRequest.getBucketLayout());
String openKey = addKeyToOpenKeyTable(allocatedLocationList);
String ozoneKey = getOzonePathKey();
OmKeyInfo omKeyInfo =
omMetadataManager.getOpenKeyTable(
omKeyCommitRequest.getBucketLayout()).get(openKey);
assertNotNull(omKeyInfo);
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OK,
omClientResponse.getOMResponse().getStatus());
// Entry should be deleted from openKey Table.
omKeyInfo =
omMetadataManager.getOpenKeyTable(omKeyCommitRequest.getBucketLayout())
.get(openKey);
assertNull(omKeyInfo);
// Now entry should be created in key Table.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNotNull(omKeyInfo);
// Check modification time
CommitKeyRequest commitKeyRequest = modifiedOmRequest.getCommitKeyRequest();
assertEquals(commitKeyRequest.getKeyArgs().getModificationTime(),
omKeyInfo.getModificationTime());
// Check block location.
assertEquals(allocatedLocationList,
omKeyInfo.getLatestVersionLocations().getLocationList());
}
@Test
public void testValidateAndUpdateCache() throws Exception {
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
KeyArgs keyArgs = modifiedOmRequest.getCommitKeyRequest().getKeyArgs();
// Append new blocks
List<OmKeyLocationInfo> allocatedLocationList =
keyArgs.getKeyLocationsList().stream()
.map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, omKeyCommitRequest.getBucketLayout());
String openKey = addKeyToOpenKeyTable(allocatedLocationList);
String ozoneKey = getOzonePathKey();
OmKeyInfo omKeyInfo =
omMetadataManager.getOpenKeyTable(
omKeyCommitRequest.getBucketLayout()).get(openKey);
assertNotNull(omKeyInfo);
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OK,
omClientResponse.getOMResponse().getStatus());
// Entry should be deleted from openKey Table.
omKeyInfo =
omMetadataManager.getOpenKeyTable(omKeyCommitRequest.getBucketLayout())
.get(openKey);
assertNull(omKeyInfo);
// Now entry should be created in key Table.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNotNull(omKeyInfo);
// DB keyInfo format
verifyKeyName(omKeyInfo);
// Check modification time
CommitKeyRequest commitKeyRequest = modifiedOmRequest.getCommitKeyRequest();
assertEquals(commitKeyRequest.getKeyArgs().getModificationTime(),
omKeyInfo.getModificationTime());
// Check block location.
List<OmKeyLocationInfo> locationInfoListFromCommitKeyRequest =
commitKeyRequest.getKeyArgs()
.getKeyLocationsList().stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
assertEquals(locationInfoListFromCommitKeyRequest,
omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(allocatedLocationList,
omKeyInfo.getLatestVersionLocations().getLocationList());
}
@Test
public void testAtomicRewrite() throws Exception {
Table<String, OmKeyInfo> openKeyTable = omMetadataManager.getOpenKeyTable(getBucketLayout());
Table<String, OmKeyInfo> closedKeyTable = omMetadataManager.getKeyTable(getBucketLayout());
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest = getOmKeyCommitRequest(modifiedOmRequest);
KeyArgs keyArgs = modifiedOmRequest.getCommitKeyRequest().getKeyArgs();
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, omKeyCommitRequest.getBucketLayout());
// Append new blocks
List<OmKeyLocationInfo> allocatedLocationList =
keyArgs.getKeyLocationsList().stream()
.map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
OmKeyInfo.Builder omKeyInfoBuilder = OMRequestTestUtils.createOmKeyInfo(
volumeName, bucketName, keyName, replicationConfig, new OmKeyLocationInfoGroup(version, new ArrayList<>()));
omKeyInfoBuilder.setExpectedDataGeneration(1L);
OmKeyInfo omKeyInfo = omKeyInfoBuilder.build();
omKeyInfo.appendNewBlocks(allocatedLocationList, false);
List<OzoneAcl> acls = Collections.singletonList(OzoneAcl.parseAcl("user:foo:rw"));
omKeyInfo.addAcl(acls.get(0));
String openKey = addKeyToOpenKeyTable(allocatedLocationList, omKeyInfo);
OmKeyInfo openKeyInfo = openKeyTable.get(openKey);
assertNotNull(openKeyInfo);
assertEquals(acls, openKeyInfo.getAcls());
// At this stage, we have an openKey, with rewrite generation of 1.
// However there is no closed key entry, so the commit should fail.
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(KEY_NOT_FOUND, omClientResponse.getOMResponse().getStatus());
// Now add the key to the key table, and try again, but with different generation
omKeyInfoBuilder.setExpectedDataGeneration(null);
omKeyInfoBuilder.setUpdateID(0L);
OmKeyInfo invalidKeyInfo = omKeyInfoBuilder.build();
closedKeyTable.put(getOzonePathKey(), invalidKeyInfo);
// This should fail as the updateID ia zero and the open key has rewrite generation of 1.
omClientResponse = omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(KEY_NOT_FOUND, omClientResponse.getOMResponse().getStatus());
omKeyInfoBuilder.setUpdateID(1L);
OmKeyInfo closedKeyInfo = omKeyInfoBuilder.build();
closedKeyTable.delete(getOzonePathKey());
closedKeyTable.put(getOzonePathKey(), closedKeyInfo);
// Now the key should commit as the updateID and rewrite Generation match.
omClientResponse = omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OK, omClientResponse.getOMResponse().getStatus());
OmKeyInfo committedKey = closedKeyTable.get(getOzonePathKey());
assertNull(committedKey.getExpectedDataGeneration());
// Generation should be changed
assertNotEquals(closedKeyInfo.getGeneration(), committedKey.getGeneration());
assertEquals(acls, committedKey.getAcls());
}
@Test
public void testValidateAndUpdateCacheWithUncommittedBlocks()
throws Exception {
// Allocated block list (5 blocks)
List<KeyLocation> allocatedKeyLocationList = getKeyLocation(5);
List<OmKeyLocationInfo> allocatedBlockList = allocatedKeyLocationList
.stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
// Commit only the first 3 allocated blocks
List<KeyLocation> committedKeyLocationList = allocatedKeyLocationList.subList(0, 3);
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest(
committedKeyLocationList, false));
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, omKeyCommitRequest.getBucketLayout());
String openKey = addKeyToOpenKeyTable(allocatedBlockList);
String ozoneKey = getOzonePathKey();
OmKeyInfo omKeyInfo =
omMetadataManager.getOpenKeyTable(
omKeyCommitRequest.getBucketLayout()).get(openKey);
assertNotNull(omKeyInfo);
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OK,
omClientResponse.getOMResponse().getStatus());
Map<String, RepeatedOmKeyInfo> toDeleteKeyList
= ((OMKeyCommitResponse) omClientResponse).getKeysToDelete();
// This is the first time to commit key, only the allocated but uncommitted
// blocks should be deleted.
assertEquals(1, toDeleteKeyList.size());
assertEquals(allocatedKeyLocationList.size() - committedKeyLocationList.size(),
toDeleteKeyList.values().stream()
.findFirst().get().cloneOmKeyInfoList().get(0).getKeyLocationVersions()
.get(0).getLocationList().size());
// Entry should be deleted from openKey Table.
omKeyInfo =
omMetadataManager.getOpenKeyTable(omKeyCommitRequest.getBucketLayout())
.get(openKey);
assertNull(omKeyInfo);
// Now entry should be created in key Table.
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNotNull(omKeyInfo);
// DB keyInfo format
verifyKeyName(omKeyInfo);
// Check modification time
CommitKeyRequest commitKeyRequest = modifiedOmRequest.getCommitKeyRequest();
assertEquals(commitKeyRequest.getKeyArgs().getModificationTime(),
omKeyInfo.getModificationTime());
// Check block location.
List<OmKeyLocationInfo> locationInfoListFromCommitKeyRequest =
commitKeyRequest.getKeyArgs()
.getKeyLocationsList().stream()
.map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
List<OmKeyLocationInfo> intersection = new ArrayList<>(allocatedBlockList);
intersection.retainAll(locationInfoListFromCommitKeyRequest);
// Key table should have three blocks.
assertEquals(intersection,
omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(3, intersection.size());
}
/**
* In these scenarios below, OM should reject key commit with HSync requested from a client:
* 1. ozone.hbase.enhancements.allowed = false, ozone.fs.hsync.enabled = false
* 2. ozone.hbase.enhancements.allowed = false, ozone.fs.hsync.enabled = true
* 3. ozone.hbase.enhancements.allowed = true, ozone.fs.hsync.enabled = false
*/
@ParameterizedTest
@CsvSource({"false,false", "false,true", "true,false"})
public void testRejectHsyncIfNotEnabled(boolean hbaseEnhancementsEnabled, boolean fsHsyncEnabled) throws Exception {
OzoneConfiguration conf = ozoneManager.getConfiguration();
conf.setBoolean(OzoneConfigKeys.OZONE_HBASE_ENHANCEMENTS_ALLOWED, hbaseEnhancementsEnabled);
conf.setBoolean("ozone.client.hbase.enhancements.allowed", true);
conf.setBoolean(OzoneConfigKeys.OZONE_FS_HSYNC_ENABLED, fsHsyncEnabled);
BucketLayout bucketLayout = getBucketLayout();
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, bucketLayout);
List<KeyLocation> allocatedKeyLocationList = getKeyLocation(10);
// hsync should throw OMException
assertThrows(OMException.class, () ->
doKeyCommit(true, allocatedKeyLocationList.subList(0, 5)));
// Regular key commit should still work
doKeyCommit(false, allocatedKeyLocationList.subList(0, 5));
// Restore config after this test run
conf.setBoolean(OzoneConfigKeys.OZONE_HBASE_ENHANCEMENTS_ALLOWED, true);
conf.setBoolean("ozone.client.hbase.enhancements.allowed", true);
conf.setBoolean(OzoneConfigKeys.OZONE_FS_HSYNC_ENABLED, true);
}
@Test
public void testCommitWithHsyncIncrementalUsages() throws Exception {
BucketLayout bucketLayout = getBucketLayout();
String bucketKey = omMetadataManager.getBucketKey(volumeName, bucketName);
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, bucketLayout);
List<KeyLocation> allocatedKeyLocationList = getKeyLocation(10);
OmBucketInfo bucketInfo = omMetadataManager.getBucketTable()
.get(bucketKey);
long usedBytes = bucketInfo.getUsedBytes();
// 1st commit of 3 blocks, HSync = true
Map<String, RepeatedOmKeyInfo> keyToDeleteMap =
doKeyCommit(true, allocatedKeyLocationList.subList(0, 3));
assertNull(keyToDeleteMap);
bucketInfo = omMetadataManager.getBucketTable().get(bucketKey);
long firstCommitUsedBytes = bucketInfo.getUsedBytes();
assertEquals(300, firstCommitUsedBytes - usedBytes);
// 2nd commit of 6 blocks, HSync = true
keyToDeleteMap = doKeyCommit(true, allocatedKeyLocationList.subList(0, 6));
assertNull(keyToDeleteMap);
bucketInfo = omMetadataManager.getBucketTable().get(bucketKey);
long secondCommitUsedBytes = bucketInfo.getUsedBytes();
assertEquals(600, secondCommitUsedBytes - usedBytes);
// 3rd and final commit of all 10 blocks, HSync = false
keyToDeleteMap = doKeyCommit(false, allocatedKeyLocationList);
// keyToDeleteMap should be null / empty because none of the previous blocks
// should be deleted.
assertTrue(keyToDeleteMap == null || keyToDeleteMap.isEmpty());
bucketInfo = omMetadataManager.getBucketTable().get(bucketKey);
long thirdCommitUsedBytes = bucketInfo.getUsedBytes();
assertEquals(1000, thirdCommitUsedBytes - usedBytes);
}
private Map<String, RepeatedOmKeyInfo> doKeyCommit(boolean isHSync,
List<KeyLocation> keyLocations) throws Exception {
// allocated block list
dataSize = keyLocations.size() * 100;
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest(
keyLocations, isHSync));
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
List<OmKeyLocationInfo> allocatedBlockList = keyLocations
.stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
String openKey = addKeyToOpenKeyTable(allocatedBlockList);
String ozoneKey = getOzonePathKey();
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OK,
omClientResponse.getOMResponse().getStatus());
// Key should be present in both OpenKeyTable and KeyTable with HSync commit
OmKeyInfo omKeyInfo =
omMetadataManager.getOpenKeyTable(
omKeyCommitRequest.getBucketLayout()).get(openKey);
if (isHSync) {
assertNotNull(omKeyInfo);
} else {
// Key should not exist in OpenKeyTable anymore with non-HSync commit
assertNull(omKeyInfo);
}
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNotNull(omKeyInfo);
return ((OMKeyCommitResponse) omClientResponse).getKeysToDelete();
}
@Test
public void testValidateAndUpdateCacheWithSubDirs() throws Exception {
parentDir = "dir1/dir2/dir3/";
keyName = parentDir + UUID.randomUUID().toString();
testValidateAndUpdateCache();
}
@Test
public void testValidateAndUpdateCacheWithVolumeNotFound() throws Exception {
OMRequest modifiedOmRequest =
doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
final long volumeId = 100L;
final long bucketID = 1000L;
final String fileName = OzoneFSUtils.getFileName(keyName);
final String ozoneKey = omMetadataManager.getOzonePathKey(volumeId,
bucketID, bucketID, fileName);
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
OmKeyInfo omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OzoneManagerProtocolProtos.Status.VOLUME_NOT_FOUND,
omClientResponse.getOMResponse().getStatus());
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
}
@Test
public void testValidateAndUpdateCacheWithBucketNotFound() throws Exception {
OMRequest modifiedOmRequest =
doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
OMRequestTestUtils.addVolumeToDB(volumeName, OzoneConsts.OZONE,
omMetadataManager);
String ozoneKey = getOzonePathKey();
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
OmKeyInfo omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OzoneManagerProtocolProtos.Status.BUCKET_NOT_FOUND,
omClientResponse.getOMResponse().getStatus());
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
}
@Test
public void testValidateAndUpdateCacheWithBucketQuotaExceeds()
throws Exception {
OMRequest modifiedOmRequest =
doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
KeyArgs keyArgs = modifiedOmRequest.getCommitKeyRequest().getKeyArgs();
// Append new blocks
List<OmKeyLocationInfo> allocatedLocationList =
keyArgs.getKeyLocationsList().stream()
.map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
OMRequestTestUtils.addVolumeToDB(volumeName, OzoneConsts.OZONE,
omMetadataManager);
OmBucketInfo.Builder bucketBuilder = OmBucketInfo.newBuilder()
.setVolumeName(volumeName)
.setBucketName(bucketName)
.setBucketLayout(omKeyCommitRequest.getBucketLayout())
.setQuotaInBytes(0L);
OMRequestTestUtils.addBucketToDB(omMetadataManager, bucketBuilder);
addKeyToOpenKeyTable(allocatedLocationList);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(OzoneManagerProtocolProtos.Status.QUOTA_EXCEEDED,
omClientResponse.getOMResponse().getStatus());
OmBucketInfo bucketInfo = omMetadataManager.getBucketTable()
.get(omMetadataManager.getBucketKey(volumeName, bucketName));
assertEquals(0, bucketInfo.getUsedNamespace());
}
@Test
public void testValidateAndUpdateCacheWithKeyNotFound() throws Exception {
OMRequest modifiedOmRequest =
doPreExecute(createCommitKeyRequest());
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(modifiedOmRequest);
OMRequestTestUtils.addVolumeAndBucketToDB(volumeName, bucketName,
omMetadataManager, omKeyCommitRequest.getBucketLayout());
String ozoneKey = getOzonePathKey();
// Key should not be there in key table, as validateAndUpdateCache is
// still not called.
OmKeyInfo omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 100L);
assertEquals(KEY_NOT_FOUND,
omClientResponse.getOMResponse().getStatus());
omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNull(omKeyInfo);
}
@Test
public void testValidateAndUpdateCacheOnOverwrite() throws Exception {
testValidateAndUpdateCache();
// This is used to generate the pseudo object ID for the suffix in deletedTable for uniqueness
when(ozoneManager.getObjectIdFromTxId(anyLong())).thenAnswer(tx ->
OmUtils.getObjectIdFromTxId(2, tx.getArgument(0)));
// Become a new client and set next version number
clientID = Time.now();
version += 1;
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest(getKeyLocation(10).subList(4, 10), false));
OMKeyCommitRequest omKeyCommitRequest = getOmKeyCommitRequest(modifiedOmRequest);
KeyArgs keyArgs = modifiedOmRequest.getCommitKeyRequest().getKeyArgs();
String ozoneKey = getOzonePathKey();
// Key should be there in key table, as validateAndUpdateCache is called.
OmKeyInfo omKeyInfo =
omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout())
.get(ozoneKey);
assertNotNull(omKeyInfo);
// Previously committed version
assertEquals(0L, omKeyInfo.getLatestVersionLocations().getVersion());
// Append new blocks
List<OmKeyLocationInfo> allocatedLocationList =
keyArgs.getKeyLocationsList().stream()
.map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
addKeyToOpenKeyTable(allocatedLocationList);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 102L);
assertEquals(OK, omClientResponse.getOMResponse().getStatus());
// New entry should be created in key Table.
omKeyInfo = omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout()).get(ozoneKey);
assertNotNull(omKeyInfo);
assertEquals(version, omKeyInfo.getLatestVersionLocations().getVersion());
// DB keyInfo format
verifyKeyName(omKeyInfo);
// Check modification time
CommitKeyRequest commitKeyRequest = modifiedOmRequest.getCommitKeyRequest();
assertEquals(commitKeyRequest.getKeyArgs().getModificationTime(), omKeyInfo.getModificationTime());
// Check block location.
List<OmKeyLocationInfo> locationInfoListFromCommitKeyRequest =
commitKeyRequest.getKeyArgs().getKeyLocationsList().stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
assertEquals(locationInfoListFromCommitKeyRequest, omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(allocatedLocationList, omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(1, omKeyInfo.getKeyLocationVersions().size());
// flush response content to db
BatchOperation batchOperation = omMetadataManager.getStore().initBatchOperation();
((OMKeyCommitResponse) omClientResponse).addToDBBatch(omMetadataManager, batchOperation);
omMetadataManager.getStore().commitBatchOperation(batchOperation);
// verify deleted key is unique generated
String deletedKey = omMetadataManager.getOzoneKey(volumeName, omKeyInfo.getBucketName(), keyName);
List<? extends Table.KeyValue<String, RepeatedOmKeyInfo>> rangeKVs
= omMetadataManager.getDeletedTable().getRangeKVs(null, 100, deletedKey);
assertThat(rangeKVs.size()).isGreaterThan(0);
Table.KeyValue<String, RepeatedOmKeyInfo> keyValue = rangeKVs.get(0);
String key = keyValue.getKey();
List<OmKeyInfo> omKeyInfoList = keyValue.getValue().getOmKeyInfoList();
assertEquals(1, omKeyInfoList.size());
assertThat(key).doesNotEndWith(String.valueOf(omKeyInfoList.get(0).getObjectID()));
}
@Test
public void testValidateAndUpdateCacheOnOverwriteWithUncommittedBlocks() throws Exception {
// Do a normal commit key (this will allocate 5 blocks
testValidateAndUpdateCache();
// This is used to generate the pseudo object ID for the suffix in deletedTable for uniqueness
when(ozoneManager.getObjectIdFromTxId(anyLong())).thenAnswer(tx ->
OmUtils.getObjectIdFromTxId(2, tx.getArgument(0)));
// Prepare the key to overwrite
// Become a new client and set next version number
clientID = Time.now();
version += 1;
String ozoneKey = getOzonePathKey();
// Previous key should be there in key table, as validateAndUpdateCache is called.
OmKeyInfo originalKeyInfo =
omMetadataManager.getKeyTable(getBucketLayout())
.get(ozoneKey);
assertNotNull(originalKeyInfo);
// Previously committed version
assertEquals(0L, originalKeyInfo.getLatestVersionLocations().getVersion());
// Allocate the subsequent 5 blocks (this should not include the initial 5 blocks from the original key)
List<KeyLocation> allocatedKeyLocationList = getKeyLocation(10).subList(5, 10);
List<OmKeyLocationInfo> allocatedBlockList = allocatedKeyLocationList
.stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
// Commit only the first 3 allocated blocks (the other 2 blocks are uncommitted)
List<KeyLocation> committedKeyLocationList = allocatedKeyLocationList.subList(0, 3);
List<OmKeyLocationInfo> committedBlockList = committedKeyLocationList
.stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
OMRequest modifiedOmRequest = doPreExecute(createCommitKeyRequest(committedKeyLocationList, false));
OMKeyCommitRequest omKeyCommitRequest = getOmKeyCommitRequest(modifiedOmRequest);
addKeyToOpenKeyTable(allocatedBlockList);
OMClientResponse omClientResponse =
omKeyCommitRequest.validateAndUpdateCache(ozoneManager, 102L);
assertEquals(OK, omClientResponse.getOMResponse().getStatus());
// New entry should be created in key Table.
OmKeyInfo omKeyInfo = omMetadataManager.getKeyTable(omKeyCommitRequest.getBucketLayout()).get(ozoneKey);
assertNotNull(omKeyInfo);
assertEquals(version, omKeyInfo.getLatestVersionLocations().getVersion());
// DB keyInfo format
verifyKeyName(omKeyInfo);
// Check modification time
CommitKeyRequest commitKeyRequest = modifiedOmRequest.getCommitKeyRequest();
assertEquals(commitKeyRequest.getKeyArgs().getModificationTime(), omKeyInfo.getModificationTime());
// Check block location.
List<OmKeyLocationInfo> locationInfoListFromCommitKeyRequest =
commitKeyRequest.getKeyArgs().getKeyLocationsList().stream().map(OmKeyLocationInfo::getFromProtobuf)
.collect(Collectors.toList());
assertEquals(locationInfoListFromCommitKeyRequest, omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(committedBlockList, omKeyInfo.getLatestVersionLocations().getLocationList());
assertEquals(1, omKeyInfo.getKeyLocationVersions().size());
Map<String, RepeatedOmKeyInfo> toDeleteKeyList
= ((OMKeyCommitResponse) omClientResponse).getKeysToDelete();
// Both the overwritten key and the uncommitted blocks should be deleted
// Both uses the same key (unlike MPU part commit request)
assertEquals(1, toDeleteKeyList.size());
List<OmKeyInfo> keysToDelete = toDeleteKeyList.values().stream()
.findFirst().get().cloneOmKeyInfoList();
assertEquals(2, keysToDelete.size());
OmKeyInfo overwrittenKey = keysToDelete.get(0);
OmKeyInfo uncommittedPseudoKey = keysToDelete.get(1);
assertEquals(DEFAULT_COMMIT_BLOCK_SIZE, overwrittenKey.getLatestVersionLocations().getLocationList().size());
assertEquals(allocatedKeyLocationList.size() - committedKeyLocationList.size(),
uncommittedPseudoKey.getLatestVersionLocations().getLocationList().size());
// flush response content to db
BatchOperation batchOperation = omMetadataManager.getStore().initBatchOperation();
((OMKeyCommitResponse) omClientResponse).addToDBBatch(omMetadataManager, batchOperation);
omMetadataManager.getStore().commitBatchOperation(batchOperation);
// verify deleted keys are stored in the deletedTable
String deletedKey = omMetadataManager.getOzoneKey(volumeName, omKeyInfo.getBucketName(), keyName);
List<? extends Table.KeyValue<String, RepeatedOmKeyInfo>> rangeKVs
= omMetadataManager.getDeletedTable().getRangeKVs(null, 100, deletedKey);
assertThat(rangeKVs.size()).isGreaterThan(0);
Table.KeyValue<String, RepeatedOmKeyInfo> keyValue = rangeKVs.get(0);
String key = keyValue.getKey();
List<OmKeyInfo> omKeyInfoList = keyValue.getValue().getOmKeyInfoList();
assertEquals(2, omKeyInfoList.size());
assertThat(key).doesNotEndWith(String.valueOf(omKeyInfoList.get(0).getObjectID()));
}
/**
* This method calls preExecute and verify the modified request.
* @param originalOMRequest
* @return OMRequest - modified request returned from preExecute.
* @throws Exception
*/
private OMRequest doPreExecute(OMRequest originalOMRequest) throws Exception {
OMKeyCommitRequest omKeyCommitRequest =
getOmKeyCommitRequest(originalOMRequest);
OMRequest modifiedOmRequest = omKeyCommitRequest.preExecute(ozoneManager);
assertTrue(modifiedOmRequest.hasCommitKeyRequest());
KeyArgs originalKeyArgs =
originalOMRequest.getCommitKeyRequest().getKeyArgs();
KeyArgs modifiedKeyArgs =
modifiedOmRequest.getCommitKeyRequest().getKeyArgs();
verifyKeyArgs(originalKeyArgs, modifiedKeyArgs);
return modifiedOmRequest;
}
/**
* Verify KeyArgs.
* @param originalKeyArgs
* @param modifiedKeyArgs
*/
private void verifyKeyArgs(KeyArgs originalKeyArgs, KeyArgs modifiedKeyArgs) {
// Check modification time is set or not.
assertThat(modifiedKeyArgs.getModificationTime()).isGreaterThan(0);
assertEquals(0, originalKeyArgs.getModificationTime());
assertEquals(originalKeyArgs.getVolumeName(),
modifiedKeyArgs.getVolumeName());
assertEquals(originalKeyArgs.getBucketName(),
modifiedKeyArgs.getBucketName());
assertEquals(originalKeyArgs.getKeyName(),
modifiedKeyArgs.getKeyName());
assertEquals(originalKeyArgs.getDataSize(),
modifiedKeyArgs.getDataSize());
assertEquals(originalKeyArgs.getKeyLocationsList(),
modifiedKeyArgs.getKeyLocationsList());
assertEquals(originalKeyArgs.getType(),
modifiedKeyArgs.getType());
assertEquals(originalKeyArgs.getFactor(),
modifiedKeyArgs.getFactor());
}
private OMRequest createCommitKeyRequest() {
return createCommitKeyRequest(false);
}
private OMRequest createCommitKeyRequest(boolean isHsync) {
return createCommitKeyRequest(getKeyLocation(DEFAULT_COMMIT_BLOCK_SIZE), isHsync);
}
/**
* Create OMRequest which encapsulates CommitKeyRequest.
*/
private OMRequest createCommitKeyRequest(
List<KeyLocation> keyLocations, boolean isHsync) {
KeyArgs keyArgs =
KeyArgs.newBuilder().setDataSize(dataSize).setVolumeName(volumeName)
.setKeyName(keyName).setBucketName(bucketName)
.setType(replicationConfig.getReplicationType())
.setFactor(((RatisReplicationConfig) replicationConfig).getReplicationFactor())
.addAllKeyLocations(keyLocations).build();
CommitKeyRequest commitKeyRequest =
CommitKeyRequest.newBuilder().setKeyArgs(keyArgs)
.setClientID(clientID).setHsync(isHsync).build();
return OMRequest.newBuilder()
.setCmdType(OzoneManagerProtocolProtos.Type.CommitKey)
.setCommitKeyRequest(commitKeyRequest)
.setClientId(UUID.randomUUID().toString()).build();
}
/**
* Create KeyLocation list.
*/
private List<KeyLocation> getKeyLocation(int count) {
List<KeyLocation> keyLocations = new ArrayList<>();
for (int i = 0; i < count; i++) {
KeyLocation keyLocation =
KeyLocation.newBuilder()
.setBlockID(HddsProtos.BlockID.newBuilder()
.setContainerBlockID(HddsProtos.ContainerBlockID.newBuilder()
.setContainerID(i + 1000).setLocalID(i + 100).build()))
.setOffset(0).setLength(200).setCreateVersion(version).build();
keyLocations.add(keyLocation);
}
return keyLocations;
}
protected String getParentDir() {
return parentDir;
}
@Nonnull
protected String getOzonePathKey() throws IOException {
return omMetadataManager.getOzoneKey(volumeName, bucketName,
keyName);
}
@Nonnull
protected String addKeyToOpenKeyTable(List<OmKeyLocationInfo> locationList)
throws Exception {
OMRequestTestUtils.addKeyToTable(true, volumeName, bucketName, keyName,
clientID, replicationConfig, omMetadataManager,
locationList, version);
return omMetadataManager.getOpenKey(volumeName, bucketName,
keyName, clientID);
}
@Nonnull
protected String addKeyToOpenKeyTable(List<OmKeyLocationInfo> locationList, OmKeyInfo keyInfo) throws Exception {
OMRequestTestUtils.addKeyToTable(true, false, keyInfo, clientID, 0, omMetadataManager);
return omMetadataManager.getOpenKey(volumeName, bucketName,
keyName, clientID);
}
@Nonnull
protected OMKeyCommitRequest getOmKeyCommitRequest(OMRequest omRequest) {
return new OMKeyCommitRequest(omRequest, BucketLayout.DEFAULT);
}
protected void verifyKeyName(OmKeyInfo omKeyInfo) {
assertEquals(keyName, omKeyInfo.getKeyName(),
"Incorrect KeyName");
String fileName = OzoneFSUtils.getFileName(keyName);
assertEquals(fileName, omKeyInfo.getFileName(),
"Incorrect FileName");
}
}
|
google/copybara | 36,926 | javatests/com/google/copybara/TransformWorkTest.java | /*
* Copyright (C) 2016 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.copybara;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.jimfs.Jimfs;
import com.google.copybara.authoring.Author;
import com.google.copybara.exception.RepoException;
import com.google.copybara.exception.ValidationException;
import com.google.copybara.revision.Change;
import com.google.copybara.revision.Changes;
import com.google.copybara.testing.DummyOrigin;
import com.google.copybara.testing.DummyRevision;
import com.google.copybara.testing.FileSubjects;
import com.google.copybara.testing.OptionsBuilder;
import com.google.copybara.testing.RecordsProcessCallDestination;
import com.google.copybara.testing.SkylarkTestExecutor;
import com.google.copybara.testing.TransformWorks;
import com.google.copybara.transform.ExplicitReversal;
import com.google.copybara.util.FileUtil;
import com.google.copybara.util.console.Message.MessageType;
import com.google.copybara.util.console.testing.TestingConsole;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TransformWorkTest {
private static final Author ORIGINAL_AUTHOR = new Author("Foo Bar", "foo@bar.com");
private SkylarkTestExecutor skylark;
private DummyOrigin origin;
private RecordsProcessCallDestination destination;
private Path workdir;
private TestingConsole console;
@Before
public void setup() throws IOException {
origin = new DummyOrigin().setAuthor(ORIGINAL_AUTHOR);
destination = new RecordsProcessCallDestination();
OptionsBuilder options = new OptionsBuilder();
console = new TestingConsole();
options.setConsole(console);
options.testingOptions.origin = origin;
options.testingOptions.destination = destination;
options.setForce(true); // We don't care about force for this test
skylark = new SkylarkTestExecutor(options);
workdir = Files.createTempDirectory("workdir");
}
@Test
public void testAddLabel() throws Exception {
checkAddLabel("foo", "foo\n\nTEST=VALUE\n");
}
@Test
public void testAddLabelToGroup() throws Exception {
checkAddLabel("foo\n\nA=B\n\n", "foo\n\nA=B\nTEST=VALUE\n");
}
@Test
public void testAddLabelNoEmptyLineBeforeGroup() throws Exception {
checkAddLabel("foo\nA=B\n\n", "foo\nA=B\n\nTEST=VALUE\n");
}
@Test
public void testAddLabelNoGroupNoEndLine() throws Exception {
checkAddLabel("foo\nA=B", "foo\nA=B\n\nTEST=VALUE\n");
}
@Test
public void testAddOrReplaceExistingLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\nother=other\n",
"ctx.add_or_replace_label('SOME', 'REPLACED')",
"Foo\n\nSOME=REPLACED\nother=other\n");
}
@Test
public void testAddTextBeforeLabels() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.add_text_before_labels('\\nFixes #1234')",
"Foo\n\nFixes #1234\n\nSOME=TEST\n");
}
@Test
public void testInvalidLabel() throws Exception {
TransformWork work = create("Foo\n\nSOME=TEST\nOTHER=FOO\n");
ValidationException e =
assertThrows(
ValidationException.class,
() -> work.removeLabel("[invalid]", /* wholeMessage= */ true));
assertThat(e).hasMessageThat().isEqualTo("Label '[invalid]' is not a valid label");
}
@Test
public void testAddHiddenLabel() throws Exception {
TransformWork work = create("Foo\n\nSOME=TEST\n");
ExplicitReversal t = skylark.eval("t", ""
+ "def user_transform(ctx):\n"
+ " " + "ctx.add_label('FOO','BAR', hidden = True)" + "\n"
+ " " + "ctx.add_label('FOO','BAR', hidden = True)" + "\n"
+ "t = core.transform([user_transform])");
t.transform(work);
assertThat(work.getMessage()).isEqualTo("Foo\n\nSOME=TEST\n");
assertThat(work.getAllLabels("FOO").getImmutableList()).isEqualTo(ImmutableList.of("BAR"));
}
@Test
public void testGetHiddenLabel() throws Exception {
TransformWork work = create("Foo\n\nSOME=TEST\n");
ExplicitReversal t = skylark.eval("t", ""
+ "def user_transform(ctx):\n"
+ " " + "ctx.add_label('FOO','ONE', hidden = True)" + "\n"
+ " " + "ctx.add_label('FOO','TWO', hidden = True)" + "\n"
+ "t = core.transform([user_transform])");
t.transform(work);
assertThat(work.getLabel("FOO")).isEqualTo("TWO");
assertThat(work.getAllLabels("FOO").getImmutableList())
.isEqualTo(ImmutableList.of("ONE", "TWO"));
}
@Test
public void testAddTwoDifferentHiddenLabels() throws Exception {
TransformWork work = create("Foo\n\nSOME=TEST\n");
ExplicitReversal t = skylark.eval("t", ""
+ "def user_transform(ctx):\n"
+ " " + "ctx.add_label('ONE','val2', hidden = True)" + "\n"
+ " " + "ctx.add_label('ONE','val2', hidden = True)" + "\n"
+ " " + "ctx.add_label('ONE','val1', hidden = True)" + "\n"
+ " " + "ctx.add_label('TWO','val2', hidden = True)" + "\n"
+ " " + "ctx.add_label('TWO','val2', hidden = True)" + "\n"
+ " " + "ctx.add_label('TWO','val1', hidden = True)" + "\n"
+ "t = core.transform([user_transform])");
t.transform(work);
assertThat(work.getAllLabels("ONE").getImmutableList())
.isEqualTo(ImmutableList.of("val2", "val1"));
assertThat(work.getAllLabels("TWO").getImmutableList())
.isEqualTo(ImmutableList.of("val2", "val1"));
}
@Test
public void testAddLabelWhitespaceInMsg() throws Exception {
checkAddLabel(" foo", " foo\n\nTEST=VALUE\n");
}
@Test
public void testAddLabelLastParagraphList() throws Exception {
checkLabelWithSkylark(""
+ "Foo\n"
+ "\n"
+ " - list\n"
+ " - other\n",
"ctx.add_label('TEST', 'VALUE')",
""
+ "Foo\n"
+ "\n"
+ " - list\n"
+ " - other\n"
+ "\n"
+ "TEST=VALUE\n");
}
@Test
public void testAddLabelLastParagraphContainsLabel() throws Exception {
checkLabelWithSkylark(""
+ "Foo\n"
+ "\n"
+ " - list\n"
+ "I_AM_A: Label\n"
+ " - other\n",
"ctx.add_label('TEST', 'VALUE')",
""
+ "Foo\n"
+ "\n"
+ " - list\n"
+ "I_AM_A: Label\n"
+ " - other\n"
+ "TEST=VALUE\n");
}
@Test
public void testAddTextBeforeLabelsNoGroup() throws Exception {
checkLabelWithSkylark("Foo\n",
"ctx.add_text_before_labels('\\nFixes #1234')",
"Foo\n\nFixes #1234\n");
}
@Test
public void testReplaceLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.replace_label('SOME', 'REPLACED')",
"Foo\n\nSOME=REPLACED\n");
}
@Test
public void testReplaceNonExistentLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nFOO=TEST\n",
"ctx.replace_label('SOME', 'REPLACED')",
"Foo\n\nFOO=TEST\n");
}
@Test
public void testReplaceNonExistentLabelNoGroup() throws Exception {
checkLabelWithSkylark("Foo\n",
"ctx.replace_label('SOME', 'REPLACED')",
"Foo\n");
}
@Test
public void testsDeleteNotFound() throws Exception {
checkLabelWithSkylark("Foo\n",
"ctx.remove_label('SOME', False)",
"Foo\n");
}
@Test
public void testsDeleteNotFound_whole() throws Exception {
checkLabelWithSkylark("Foo\n",
"ctx.remove_label('SOME', True)",
"Foo\n");
}
@Test
public void testsDeleteLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.remove_label('SOME', False)",
"Foo\n");
}
@Test
public void testsDeleteLabel_whole() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.remove_label('SOME', True)",
"Foo\n");
}
@Test
public void testsDeleteOnlyOneLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\nOTHER=aaa\n",
"ctx.remove_label('SOME', False)",
"Foo\n\nOTHER=aaa\n");
}
@Test
public void testsDeleteOnlyOneLabel_whole() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\nOTHER=aaa\n",
"ctx.remove_label('SOME', True)",
"Foo\n\nOTHER=aaa\n");
}
@Test
public void testsDeleteNonExistentLabel() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.remove_label('FOO', False)",
"Foo\n\nSOME=TEST\n");
}
@Test
public void testsDeleteNonExistentLabel_whole() throws Exception {
checkLabelWithSkylark("Foo\n\nSOME=TEST\n",
"ctx.remove_label('FOO', True)",
"Foo\n\nSOME=TEST\n");
}
private Change<DummyRevision> toChange(DummyRevision dummyRevision) {
return TransformWorks.toChange(dummyRevision, ORIGINAL_AUTHOR);
}
@Test
public void testDateFormat() throws Exception {
checkLabelWithSkylark("", "ctx.set_message(ctx.now_as_string())",
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(ZonedDateTime.now(ZoneOffset.UTC)));
boolean isDst = TimeZone.getTimeZone("Europe/Madrid").inDaylightTime(new Date());
checkLabelWithSkylark("",
"ctx.set_message(ctx.now_as_string('yyyy MM dd XXX', 'Europe/Madrid'))",
DateTimeFormatter.ofPattern("yyyy MM dd").format(
ZonedDateTime.now(ZoneId.of("Europe/Madrid"))) + (isDst ? " +02:00" : " +01:00"));
checkLabelWithSkylark("",
"ctx.set_message(ctx.now_as_string('yyyy MM dd VV', 'Europe/Madrid'))",
DateTimeFormatter.ofPattern("yyyy MM dd").format(
ZonedDateTime.now(ZoneId.of("Europe/Madrid"))) + " Europe/Madrid");
}
@Test
public void testGetLabel() {
TransformWork work =
create("Foo\n\nSOME=TEST\n")
.withChanges(
new Changes(
ImmutableList.of(
toChange(
new DummyRevision("1")
.withLabels(
ImmutableListMultimap.of(
"ONE", "one", "SOME", "SHOULD_NOT_HAPPEN"))),
toChange(
new DummyRevision("2")
.withLabels(ImmutableListMultimap.of("TWO", "two"))),
toChange(
new DummyRevision("3")
.withLabels(ImmutableListMultimap.of("THREE", "three")))),
ImmutableList.of()))
.withResolvedReference(
new DummyRevision("resolved")
.withLabels(
ImmutableListMultimap.of(
"RESOLVED",
"resolved",
"ONE",
"SHOULD_NOT_HAPPEN",
"SOME",
"SHOULD_NOT_HAPPEN")));
work.setAuthor(ORIGINAL_AUTHOR);
assertThat(work.getAllLabels("COPYBARA_AUTHOR")).containsExactly("Foo Bar", "foo@bar.com");
assertThat(work.getLabel("SOME")).isEqualTo("TEST");
assertThat(work.getLabel("ONE")).isEqualTo("one");
assertThat(work.getLabel("TWO")).isEqualTo("two");
assertThat(work.getLabel("THREE")).isEqualTo("three");
assertThat(work.getLabel("RESOLVED")).isEqualTo("resolved");
assertThat(work.getLabel("FOO")).isEqualTo(null);
}
@Test
public void testGetDateLabel_null() {
TransformWork workNullTime = create("Foo\n\nSOME=TEST\n")
.withCurrentRev(new DummyRevision("1").withTimestamp(null));
assertThat(workNullTime.getLabel("COPYBARA_CURRENT_REV_DATE_TIME")).isEqualTo(null);
}
@Test
public void testGetDateLabel_value() {
TransformWork work = create("Foo\n\nSOME=TEST\n")
.withCurrentRev(new DummyRevision("1")
.withTimestamp(ZonedDateTime.ofInstant(
Instant.ofEpochSecond(1591743457), ZoneId.of("UTC"))));
assertThat(work.getLabel("COPYBARA_CURRENT_REV_DATE_TIME")).isEqualTo("2020-06-09T22:57:37Z");
}
@Test
public void testReversible() throws ValidationException {
TransformWork work = create("Foo\n\nSOME=TEST\nOTHER=FOO\n");
work.addOrReplaceLabel("EXAMPLE", "VALUE", "=");
work.replaceLabel("EXAMPLE", "OTHER VALUE", "=", true);
assertThat(work.getMessage()).isEqualTo("Foo\n\nSOME=TEST\nOTHER=FOO\nEXAMPLE=OTHER VALUE\n");
work.removeLabel("EXAMPLE", /*wholeMessage=*/true);
assertThat(work.getMessage()).isEqualTo("Foo\n\nSOME=TEST\nOTHER=FOO\n");
}
@Test
public void testGetLabelFromCurrentRev_whenNoChangesMigrated() {
TransformWork work =
create("Foo :)")
.withChanges(new Changes(ImmutableList.of(), ImmutableList.of()))
.withCurrentRev(
new DummyRevision("foo")
.withLabels(ImmutableListMultimap.of("CURRENT_VERSION", "1")))
.withResolvedReference(
new DummyRevision("foo")
.withLabels(ImmutableListMultimap.of("CURRENT_VERSION", "2")));
assertThat(work.getLabel("CURRENT_VERSION")).isEqualTo("1");
}
@Test
public void testConsole() throws IOException, ValidationException, RepoException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("foo");
touchFile(base.resolve("not_important.txt"), "");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " ctx.console.progress('Progress message')\n"
+ " ctx.console.info('Informational message')\n"
+ " ctx.console.warn('Warning message')\n");
console.assertThat().onceInLog(MessageType.PROGRESS, "Progress message");
console.assertThat().onceInLog(MessageType.INFO, "Informational message");
console.assertThat().onceInLog(MessageType.WARNING, "Warning message");
}
@Test
public void testConsoleError() throws IOException, ValidationException, RepoException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("foo");
touchFile(base.resolve("not_important.txt"), "");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
ValidationException e =
assertThrows(
ValidationException.class,
() ->
runWorkflow(
"test",
""
+ "def test(ctx):\n"
+ " ctx.console.error('Error message')\n"
+ " ctx.console.error('Another error message')\n"));
assertThat(e).hasMessageThat().isEqualTo("2 error(s) while executing test");
console
.assertThat()
.onceInLog(MessageType.ERROR, "Error message")
.onceInLog(MessageType.ERROR, "Another error message");
}
@Test
public void testWithCurrentRev() {
assertThat(TransformWorks.of(workdir, "test", console).withCurrentRev(new DummyRevision("a"))
.isInsideExplicitTransform()).isFalse();
}
@Test
public void testWithConsole() {
assertThat(TransformWorks.of(workdir, "test", console)
.insideExplicitTransform()
.withConsole(console)
.isInsideExplicitTransform()).isTrue();
}
@Test
public void testRunGlob() throws IOException, ValidationException, RepoException {
checkGlob("run");
}
@Test
public void testRunGlobWithList() throws IOException, ValidationException, RepoException {
checkGlob("list");
}
private void checkGlob(String method) throws IOException, RepoException, ValidationException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("testRunGlob");
touchFile(base, "folder/file.txt");
touchFile(base, "folder/subfolder/file.txt");
touchFile(base, "folder/subfolder/file.java");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " message = ''\n"
+ " for f in sorted(ctx." + method + "(glob(['**']))):\n"
+ " message += f.path +'\\n'\n"
+ " ctx.set_message(message)");
assertThat(destination.processed.get(0).getChangesSummary()).isEqualTo(""
+ "folder/file.txt\n"
+ "folder/subfolder/file.java\n"
+ "folder/subfolder/file.txt\n"
);
}
@Test
public void testCreateSymlink() throws Exception {
checkCreateSymlink("a/b/c/d1", "a/b/c/d2");
checkCreateSymlink("a/b/c/d1", "a/b/d/d2");
checkCreateSymlink("a/b/c/d1", "a/d/e/d2");
checkCreateSymlink("a/d1", "a/b/c/d1");
checkCreateSymlink("f1", "f2");
checkCreateSymlink("a/d1", "d2");
checkCreateSymlink("d1", "b/d2");
ValidationException regularFile =
assertThrows(ValidationException.class, () -> checkCreateSymlink("d1", "d1"));
assertThat(regularFile).hasMessageThat().contains("'d1' already exist and is a regular file");
}
@Test
public void testCreateSymlinkDir() throws Exception {
FileSystem fileSystem = Jimfs.newFileSystem();
FileUtil.deleteRecursively(workdir);
Path base = fileSystem.getPath("testRunGlob");
writeFile(base, "b/test.txt", "FOOOO");
origin.addChange(0, base, "message", /*matchesGlob=*/true);
Path[] workdir = new Path[]{null};
destination.onWrite(transformResult -> workdir[0] = transformResult.getPath());
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " ctx.create_symlink(ctx.new_path('a'), ctx.new_path('b'))\n");
assertThat(workdir[0] != null).isTrue();
FileSubjects.assertThatPath(workdir[0])
.containsFile("b/test.txt", "FOOOO")
.containsFile("a/test.txt", "FOOOO")
.containsSymlink("a", "b")
.containsNoMoreFiles();
}
private void checkCreateSymlink(String link, String target)
throws IOException, RepoException, ValidationException {
FileSystem fileSystem = Jimfs.newFileSystem();
FileUtil.deleteRecursively(workdir);
Path base = fileSystem.getPath("testRunGlob");
writeFile(base, target, "FOOOO");
origin.addChange(0, base, "message", /*matchesGlob=*/true);
Path[] workdir = new Path[]{null};
destination.onWrite(transformResult -> workdir[0] = transformResult.getPath());
runWorkflow("test", String.format(""
+ "def test(ctx):\n"
+ " ctx.create_symlink(ctx.new_path('%s'), ctx.new_path('%s'))\n",
link, target));
assertThat(workdir[0] != null).isTrue();
FileSubjects.assertThatPath(workdir[0])
.containsFile(target, "FOOOO")
.containsSymlink(link, target)
.containsNoMoreFiles();
}
@Test
public void testRunDynamicTransforms() throws IOException, ValidationException, RepoException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("testRunDynamicTransforms");
touchFile(base, "folder/file1.txt");
touchFile(base, "folder/file2.txt");
touchFile(base, "folder/file3.txt");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " message = ''\n"
+ " for f in ctx.run(glob(['**.txt'])):\n"
+ " ctx.run(core.move(f.path, 'other/folder/prefix_' + f.name))");
assertThat(destination.processed.get(0).getWorkdir().keySet()).containsExactly(
"other/folder/prefix_file1.txt",
"other/folder/prefix_file2.txt",
"other/folder/prefix_file3.txt");
}
@Test
public void testReadAndWrite() throws IOException, ValidationException, RepoException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("testRunDynamicTransforms");
writeFile(base, "folder/file.txt", "foo");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
String now = DateTimeFormatter.ofPattern("yyyy-MM-dd")
.format(ZonedDateTime.now(ZoneOffset.UTC));
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " path = ctx.new_path('folder/file.txt')\n"
+ " ctx.read_path(path)\n"
+ " ctx.write_path(path, ctx.read_path(path) + ctx.now_as_string())");
assertThat(destination.processed.get(0).getWorkdir())
.containsEntry("folder/file.txt", "foo" + now);
}
@Test
public void testWriteCreatesSubdirs() throws Exception {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("testRunDynamicTransforms");
writeFile(base, "folder/file.txt", "foo");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " path = ctx.new_path('folder/file.txt')\n"
+ " contents = ctx.read_path(path)\n"
+ " ctx.write_path(ctx.new_path('other_folder/other_file.txt'), contents)");
assertThat(destination.processed.get(0).getWorkdir())
.containsEntry("other_folder/other_file.txt", "foo");
}
@Test
public void testTreeStateRestored() throws IOException, ValidationException, RepoException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("testTreeStateRestored");
writeFile(base, "folder/file1.txt", "aaa");
writeFile(base, "folder/file2.txt", "aaa");
writeFile(base, "folder/file3.txt", "aaa");
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " message = ''\n"
+ " for f in ctx.run(glob(['**.txt'])):\n"
+ " ctx.run(core.move(f.path, 'prefix_' + f.name))\n"
+ " ctx.run(core.replace("
+ "before ='aaa', after = 'bbb', paths = glob(['prefix_' + f.name])))");
assertThat(destination.processed.get(0).getWorkdir())
.containsExactlyEntriesIn(ImmutableMap.of(
"prefix_file1.txt", "bbb",
"prefix_file2.txt", "bbb",
"prefix_file3.txt", "bbb"));
}
@Test
public void testRunFileOps() throws IOException, ValidationException, RepoException {
checkPathOperations("folder/file.txt", ""
+ "path: folder/file.txt\n"
+ "name: file.txt\n"
+ "file exists: True\n"
+ "sibling path: folder/baz.txt\n"
+ "parent path: folder\n"
+ "parent parent path: \n"
+ "parent parent parent: None\n", true);
}
@Test
public void testRunFileOpsSubSubFolder() throws IOException, ValidationException, RepoException {
checkPathOperations("folder/other/file.txt", ""
+ "path: folder/other/file.txt\n"
+ "name: file.txt\n"
+ "file exists: False\n"
+ "sibling path: folder/other/baz.txt\n"
+ "parent path: folder/other\n"
+ "parent parent path: folder\n"
+ "parent parent parent: \n", false);
}
private void checkPathOperations(String filePath, String output, boolean createFile)
throws IOException, RepoException, ValidationException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("foo");
touchFile(base.resolve("not_important.txt"), "");
Files.createDirectories(workdir.resolve("folder"));
if (createFile) {
touchFile(base.resolve(filePath), "");
}
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", ""
+ "def test(ctx):\n"
+ " f = ctx.new_path('" + filePath + "')\n"
+ " message = 'path: ' + f.path +'\\n'\n"
+ " message += 'name: ' + f.name +'\\n'\n"
+ " message += 'file exists: ' + str(f.exists()) +'\\n'\n"
+ " message += 'sibling path: ' + f.resolve_sibling('baz.txt').path + '\\n'\n"
+ " message += 'parent path: ' + f.parent.path + '\\n'\n"
+ " message += 'parent parent path: ' + f.parent.parent.path + '\\n'\n"
+ " message += 'parent parent parent: ' + str(f.parent.parent.parent) + '\\n'\n"
+ " ctx.set_message(message)");
assertThat(destination.processed.get(0).getChangesSummary()).isEqualTo(
output);
}
@Test
public void testAttrSize() throws RepoException, IOException, ValidationException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("foo");
Files.createDirectories(base);
Files.write(base.resolve("file.txt"), "1234567890".getBytes(UTF_8));
Files.createDirectories(workdir.resolve("folder"));
origin.addChange(0, base, "message", /*matchesGlob=*/true);
runWorkflow("test", "def test(ctx):\n"
+ " size = ctx.run(glob(['**.txt']))[0].attr.size\n"
+ " ctx.console.info('File size: ' + str(size))");
console.assertThat().onceInLog(MessageType.INFO, "File size: 10");
}
@Test
public void testSymlinks_escape() throws Exception {
Path base = Files.createDirectories(workdir.resolve("foo"));
Path badTarget = Files.createTempFile("badPrefix", "THE CONTENT");
Path badLink =
Files.createSymbolicLink(
Files.createDirectory(base.resolve("a")).resolve("file.txt"), badTarget);
Files.createSymbolicLink(base.resolve("a/chained.txt"), badLink);
Transformation readEscapedSymlink =
skylark.eval(
"transformation",
"""
def test(ctx):
path = ctx.new_path("foo/a/file.txt")
ctx.console.info(ctx.read_path(path))
transformation = core.transform([test])
""");
ValidationException veRead =
assertThrows(
ValidationException.class,
() -> readEscapedSymlink.transform(TransformWorks.of(workdir, "test", console)));
assertThat(veRead).hasMessageThat().contains("is not inside the checkout directory");
Transformation writeEscapedSymlink =
skylark.eval(
"transformation",
"""
def test(ctx):
path = ctx.new_path("foo/a/file.txt")
ctx.console.info(ctx.write_path(path, "foo"))
transformation = core.transform([test])
""");
ValidationException veWrite =
assertThrows(
ValidationException.class,
() -> writeEscapedSymlink.transform(TransformWorks.of(workdir, "test", console)));
assertThat(veWrite).hasMessageThat().contains("is not inside the checkout directory");
}
@Test
public void symlinks_withCwdSymlink_worksCorrectly() throws Exception {
workdir = Files.createSymbolicLink(workdir.resolve("symlink"), workdir).resolve("nested_workdir");
Path base = Files.createDirectories(workdir.resolve("foo"));
Files.write(
Files.createDirectory(base.resolve("a")).resolve("file.txt"),
"THE CONTENT".getBytes(UTF_8));
Files.createSymbolicLink(
Files.createDirectory(base.resolve("b")).resolve("file.txt"), Paths.get("../a/file.txt"));
Files.write(
Files.createDirectories(base.resolve("c/folder")).resolve("file.txt"),
"THE CONTENT2".getBytes(UTF_8));
Files.createSymbolicLink(base.resolve("c/file.txt"), Paths.get("folder/file.txt"));
Transformation transformation =
skylark.eval(
"transformation",
"def test(ctx):\n"
+ " for f in ctx.run(glob(['**'])):\n"
+ " ctx.console.info(f.path + ':' + str(f.attr.symlink))\n"
+ " if f.attr.symlink:\n"
+ " target = f.read_symlink()\n"
+ " ctx.console.info(f.path + ' -> ' + target.path)\n"
+ " ctx.console.info(f.path + ' content ' + ctx.read_path(f))\n"
+ " ctx.console.info(target.path + ' content ' +"
+ " ctx.read_path(target))\n"
+ "\n"
+ "transformation = core.transform([test])");
transformation.transform(TransformWorks.of(workdir, "test", console));
console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt:False");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt:True");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt -> foo/a/file.txt");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt content THE CONTENT");
console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt content THE CONTENT");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt:True");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt:False");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt -> foo/c/folder/file.txt");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt content THE CONTENT2");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt content THE CONTENT2");
}
@Test
public void testSymlinks() throws Exception {
Path base = Files.createDirectories(workdir.resolve("foo"));
Files.write(Files.createDirectory(base.resolve("a")).resolve("file.txt"),
"THE CONTENT".getBytes(UTF_8));
Files.createSymbolicLink(Files.createDirectory(base.resolve("b")).resolve("file.txt"),
Paths.get("../a/file.txt"));
Files.write(Files.createDirectories(base.resolve("c/folder")).resolve("file.txt"),
"THE CONTENT2".getBytes(UTF_8));
Files.createSymbolicLink(base.resolve("c/file.txt"), Paths.get("folder/file.txt"));
Transformation transformation = skylark.eval("transformation", ""
+ "def test(ctx):\n"
+ " for f in ctx.run(glob(['**'])):\n"
+ " ctx.console.info(f.path + ':' + str(f.attr.symlink))\n"
+ " if f.attr.symlink:\n"
+ " target = f.read_symlink()\n"
+ " ctx.console.info(f.path + ' -> ' + target.path)\n"
+ " ctx.console.info(f.path + ' content ' + ctx.read_path(f))\n"
+ " ctx.console.info(target.path + ' content ' + ctx.read_path(target))\n"
+ "\n"
+ "transformation = core.transform([test])");
transformation.transform(TransformWorks.of(workdir, "test", console));
console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt:False");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt:True");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt -> foo/a/file.txt");
console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt content THE CONTENT");
console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt content THE CONTENT");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt:True");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt:False");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt -> foo/c/folder/file.txt");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt content THE CONTENT2");
console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt content THE CONTENT2");
}
@Test
public void testSymlinks_outside() throws IOException, ValidationException {
Path base = Files.createDirectories(workdir.resolve("foo"));
Path tempFile = Files.createTempFile("foo", "bar");
Files.write(tempFile, "THE CONTENT".getBytes(UTF_8));
Files.createSymbolicLink(base.resolve("symlink"), tempFile);
Transformation transformation = skylark.eval("transformation", ""
+ "def test(ctx):\n"
+ " ctx.new_path('foo/symlink').read_symlink()\n"
+ "\n"
+ "transformation = core.transform([test])");
ValidationException e =
assertThrows(
ValidationException.class,
() -> transformation.transform(TransformWorks.of(workdir, "test", console)));
assertThat(e).hasMessageThat().contains("points to a file outside the checkout dir");
}
@Test
public void testPathOperations_withCoreReplace() throws Exception {
Files.write(workdir.resolve("file1.txt"), "contents of file 1; x".getBytes(UTF_8));
Transformation transformation = skylark.eval("transformation", ""
+ "def test(ctx):\n"
+ " ctx.run(core.replace('x', 'y'))\n"
+ " ctx.write_path(ctx.new_path('file2.txt'), 'contents of file 2; y')\n"
+ " ctx.run(core.replace('y', 'z'))\n"
+ "\n"
+ "transformation = core.transform([test])");
TransformWork work = TransformWorks.of(workdir, "test", console);
transformation.transform(work);
assertThat(Files.readAllLines(workdir.resolve("file1.txt")))
.containsExactly("contents of file 1; z");
assertThat(Files.readAllLines(workdir.resolve("file2.txt")))
.containsExactly("contents of file 2; z");
}
@Test
public void testPathOperations_setExecutable() throws Exception {
Files.write(workdir.resolve("file1.txt"), "contents of file1".getBytes(UTF_8));
Files.write(workdir.resolve("file2.txt"), "contents of file2".getBytes(UTF_8));
workdir.resolve("file2.txt").toFile().setExecutable(true);
Transformation transformation =
skylark.eval(
"transformation",
""
+ "def test(ctx):\n"
+ " ctx.set_executable(ctx.new_path('file1.txt'), True)\n"
+ " ctx.set_executable(ctx.new_path('file2.txt'), False)\n"
+ "\n"
+ "transformation = core.transform([test])");
TransformWork work = TransformWorks.of(workdir, "test", console);
transformation.transform(work);
assertThat(Files.isExecutable(workdir.resolve("file1.txt"))).isTrue();
assertThat(Files.isExecutable(workdir.resolve("file2.txt"))).isFalse();
}
private void touchFile(Path base, String path) throws IOException {
writeFile(base, path, "");
}
private void writeFile(Path base, String path, String content) throws IOException {
Files.createDirectories(base.resolve(path).getParent());
Files.write(base.resolve(path), content.getBytes(UTF_8));
}
private void runWorkflow(String functionName, String function)
throws RepoException, IOException, ValidationException {
skylark.loadConfig(""
+ function + "\n"
+ "core.workflow(\n"
+ " name = 'default',\n"
+ " origin = testing.origin(),\n"
+ " destination = testing.destination(),\n"
+ " transformations = [" + functionName + "],\n"
+ " authoring = authoring.pass_thru('foo <foo@foo.com>'),\n"
+ ")\n").getMigration("default").run(workdir, ImmutableList.of());
}
private void checkAddLabel(String originalMsg, String expected) throws Exception {
checkLabelWithSkylark(originalMsg,
"ctx.add_label('TEST','VALUE')",
expected);
checkLabelWithSkylark(originalMsg,
"ctx.add_or_replace_label('TEST','VALUE')",
expected);
}
private TransformWork create(String msg) {
return TransformWorks.of(FileSystems.getDefault().getPath("/"), msg, console);
}
private void checkLabelWithSkylark(String originalMsg, String transform,
String expectedOutputMsg)
throws Exception {
TransformWork work = create(originalMsg);
ExplicitReversal t = skylark.eval("t", ""
+ "def user_transform(ctx):\n"
+ " " + transform + "\n"
+ "t = core.transform([user_transform])");
t.transform(work);
assertThat(work.getMessage()).isEqualTo(expectedOutputMsg);
}
}
|
apache/drill | 38,241 | exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillOptiq.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.planner.logical;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import org.apache.calcite.avatica.util.TimeUnit;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.type.BasicSqlType;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.util.DateString;
import org.apache.calcite.util.TimeString;
import org.apache.calcite.util.TimestampString;
import org.apache.commons.lang3.StringUtils;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.expression.ExpressionPosition;
import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.expression.FunctionCallFactory;
import org.apache.drill.common.expression.IfExpression;
import org.apache.drill.common.expression.IfExpression.IfCondition;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.NullExpression;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.expression.TypedNullConstant;
import org.apache.drill.common.expression.ValueExpressions;
import org.apache.drill.common.expression.ValueExpressions.QuotedString;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.Types;
import org.apache.drill.exec.alias.AliasRegistry;
import org.apache.drill.exec.alias.AliasRegistryProvider;
import org.apache.drill.exec.planner.StarColumnHelper;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexCorrelVariable;
import org.apache.calcite.rex.RexDynamicParam;
import org.apache.calcite.rex.RexFieldAccess;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexLocalRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexOver;
import org.apache.calcite.rex.RexRangeRef;
import org.apache.calcite.rex.RexVisitorImpl;
import org.apache.calcite.sql.SqlSyntax;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.util.NlsString;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.drill.exec.planner.physical.PlannerSettings;
import org.apache.drill.exec.work.ExecErrorConstants;
import static org.apache.drill.exec.planner.physical.PlannerSettings.ENABLE_DECIMAL_DATA_TYPE;
/**
* Utilities for Drill's planner.
*/
public class DrillOptiq {
public static final String UNSUPPORTED_REX_NODE_ERROR = "Cannot convert RexNode to equivalent Drill expression. ";
private static final Logger logger = LoggerFactory.getLogger(DrillOptiq.class);
/**
* Converts a tree of {@link RexNode} operators into a scalar expression in Drill syntax using one input.
*
* @param context parse context which contains planner settings
* @param input data input
* @param expr expression to be converted
* @return converted expression
*/
public static LogicalExpression toDrill(DrillParseContext context, RelNode input, RexNode expr) {
return toDrill(context, Lists.newArrayList(input), expr);
}
/**
* Converts a tree of {@link RexNode} operators into a scalar expression in Drill syntax using multiple inputs.
*
* @param context parse context which contains planner settings
* @param inputs multiple data inputs
* @param expr expression to be converted
* @return converted expression
*/
public static LogicalExpression toDrill(DrillParseContext context, List<RelNode> inputs, RexNode expr) {
final RexToDrill visitor = new RexToDrill(context, inputs);
return expr.accept(visitor);
}
public static LogicalExpression toDrill(DrillParseContext context, RelDataType type,
RexBuilder builder, RexNode expr) {
final RexToDrill visitor = new RexToDrill(context, type, builder);
return expr.accept(visitor);
}
public static class RexToDrill extends RexVisitorImpl<LogicalExpression> {
private final DrillParseContext context;
private final List<RelDataTypeField> fieldList;
private final RelDataType rowType;
private final RexBuilder builder;
RexToDrill(DrillParseContext context, List<RelNode> inputs) {
super(true);
this.context = context;
this.fieldList = new ArrayList<>();
if (inputs.size() > 0 && inputs.get(0)!=null) {
this.rowType = inputs.get(0).getRowType();
this.builder = inputs.get(0).getCluster().getRexBuilder();
}
else {
this.rowType = null;
this.builder = null;
}
/*
Fields are enumerated by their presence order in input. Details {@link org.apache.calcite.rex.RexInputRef}.
Thus we can merge field list from several inputs by adding them into the list in order of appearance.
Each field index in the list will match field index in the RexInputRef instance which will allow us
to retrieve field from filed list by index in {@link #visitInputRef(RexInputRef)} method. Example:
Query: select t1.c1, t2.c1. t2.c2 from t1 inner join t2 on t1.c1 between t2.c1 and t2.c2
Input 1: $0
Input 2: $1, $2
Result: $0, $1, $2
*/
for (RelNode input : inputs) {
if (input != null) {
fieldList.addAll(input.getRowType().getFieldList());
}
}
}
public RexToDrill(DrillParseContext context, RelNode input) {
this(context, Lists.newArrayList(input));
}
public RexToDrill(DrillParseContext context, RelDataType rowType, RexBuilder builder) {
super(true);
this.context = context;
this.rowType = rowType;
this.builder = builder;
this.fieldList = rowType.getFieldList();
}
protected RelDataType getRowType() {
return rowType;
}
protected RexBuilder getRexBuilder() {
return builder;
}
@Override
public LogicalExpression visitInputRef(RexInputRef inputRef) {
final int index = inputRef.getIndex();
final RelDataTypeField field = fieldList.get(index);
return FieldReference.getWithQuotedRef(field.getName());
}
@Override
public LogicalExpression visitCall(RexCall call) {
// logger.debug("RexCall {}, {}", call);
final SqlSyntax syntax = call.getOperator().getSyntax();
switch (syntax) {
case BINARY:
logger.debug("Binary");
final String funcName = call.getOperator().getName().toLowerCase();
return doFunction(call, funcName);
case FUNCTION:
case FUNCTION_ID:
logger.debug("Function");
return getDrillFunctionFromOptiqCall(call);
case POSTFIX:
logger.debug("Postfix");
switch(call.getKind()){
case IS_NOT_NULL:
case IS_NOT_TRUE:
case IS_NOT_FALSE:
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
case OTHER:
return FunctionCallFactory.createExpression(call.getOperator().getName().toLowerCase(),
ExpressionPosition.UNKNOWN, call.getOperands().get(0).accept(this));
default:
throw notImplementedException(syntax, call);
}
case PREFIX:
LogicalExpression arg = call.getOperands().get(0).accept(this);
switch(call.getKind()){
case NOT:
return FunctionCallFactory.createExpression(call.getOperator().getName().toLowerCase(),
ExpressionPosition.UNKNOWN, arg);
case MINUS_PREFIX:
List<LogicalExpression> operands = new ArrayList<>();
operands.add(call.getOperands().get(0).accept(this));
return FunctionCallFactory.createExpression("u-", operands);
default:
throw notImplementedException(syntax, call);
}
case SPECIAL:
switch(call.getKind()){
case CAST:
return getDrillCastFunctionFromOptiq(call);
case ROW:
List<RelDataTypeField> fieldList = call.getType().getFieldList();
List<RexNode> oldOperands = call.getOperands();
List<LogicalExpression> newOperands = new ArrayList<>();
for (int i = 0; i < oldOperands.size(); i++) {
RexLiteral nameOperand = getRexBuilder().makeLiteral(fieldList.get(i).getName());
RexNode valueOperand = call.operands.get(i);
newOperands.add(nameOperand.accept(this));
newOperands.add(valueOperand.accept(this));
}
return FunctionCallFactory.createExpression(call.op.getName().toLowerCase(), newOperands);
case LIKE:
case SIMILAR:
return getDrillFunctionFromOptiqCall(call);
case CASE:
List<LogicalExpression> caseArgs = new ArrayList<>();
for(RexNode r : call.getOperands()){
caseArgs.add(r.accept(this));
}
caseArgs = Lists.reverse(caseArgs);
// number of arguements are always going to be odd, because
// Optiq adds "null" for the missing else expression at the end
assert caseArgs.size()%2 == 1;
LogicalExpression elseExpression = caseArgs.get(0);
for (int i=1; i<caseArgs.size(); i=i+2) {
elseExpression = IfExpression.newBuilder()
.setElse(elseExpression)
.setIfCondition(new IfCondition(caseArgs.get(i + 1), caseArgs.get(i))).build();
}
return elseExpression;
default:
}
if (call.getOperator() == SqlStdOperatorTable.ITEM) {
return handleItemOperator(call, syntax);
}
if (call.getOperator() == SqlStdOperatorTable.DATETIME_PLUS) {
return doFunction(call, "+");
}
if (call.getOperator() == SqlStdOperatorTable.MINUS_DATE) {
return doFunction(call, "-");
}
case INTERNAL:
if (call.getOperator() == SqlStdOperatorTable.SEARCH) {
return RexUtil.expandSearch(getRexBuilder(), null, call).accept(this);
}
// fall through
default:
throw notImplementedException(syntax, call);
}
}
private SchemaPath handleItemOperator(RexCall call, SqlSyntax syntax) {
SchemaPath left = (SchemaPath) call.getOperands().get(0).accept(this);
RelDataType dataType = call.getOperands().get(0).getType();
boolean isMap = dataType.getSqlTypeName() == SqlTypeName.MAP;
// Convert expr of item[*, 'abc'] into column expression 'abc'
String rootSegName = left.getRootSegment().getPath();
if (StarColumnHelper.isStarColumn(rootSegName)) {
rootSegName = rootSegName.substring(0, rootSegName.indexOf(SchemaPath.DYNAMIC_STAR));
final RexLiteral literal = (RexLiteral) call.getOperands().get(1);
return SchemaPath.getSimplePath(rootSegName + literal.getValue2().toString());
}
final RexLiteral literal;
RexNode operand = call.getOperands().get(1);
if (operand instanceof RexLiteral) {
literal = (RexLiteral) operand;
} else if (isMap && operand.getKind() == SqlKind.CAST) {
SqlTypeName castType = operand.getType().getSqlTypeName();
SqlTypeName keyType = dataType.getKeyType().getSqlTypeName();
Preconditions.checkArgument(castType == keyType,
String.format("Wrong type CAST: expected '%s' but found '%s'", keyType.getName(), castType.getName()));
literal = (RexLiteral) ((RexCall) operand).operands.get(0);
} else {
throw notImplementedException(syntax, call);
}
switch (literal.getTypeName()) {
case DECIMAL:
case INTEGER:
if (isMap) {
return handleMapNumericKey(literal, operand, dataType, left);
}
return left.getChild(((BigDecimal) literal.getValue()).intValue());
case CHAR:
case TIMESTAMP:
case TIME:
case DATE:
if (isMap) {
return handleMapCharKey(literal, operand, dataType, left);
}
return left.getChild(literal.getValue2().toString());
case BOOLEAN:
if (isMap) {
BasicSqlType sqlType = (BasicSqlType) operand.getType();
TypeProtos.DataMode mode = sqlType.isNullable() ? TypeProtos.DataMode.OPTIONAL : TypeProtos.DataMode.REQUIRED;
return left.getChild(literal.getValue().toString(), literal.getValue(), Types.withMode(MinorType.BIT, mode));
}
// fall through
default:
throw notImplementedException(syntax, call);
}
}
private DrillRuntimeException notImplementedException(SqlSyntax syntax, RexCall call) {
String message = String.format("Syntax '%s(%s)' is not implemented.", syntax.toString(), call.toString());
throw new DrillRuntimeException(message);
}
private SchemaPath handleMapNumericKey(RexLiteral literal, RexNode operand, RelDataType mapType, SchemaPath parentPath) {
BigDecimal literalValue = (BigDecimal) literal.getValue();
RelDataType sqlType = operand.getType();
Object originalValue;
TypeProtos.DataMode mode = sqlType.isNullable() ? TypeProtos.DataMode.OPTIONAL : TypeProtos.DataMode.REQUIRED;
boolean arraySegment = false;
MajorType type;
switch (mapType.getKeyType().getSqlTypeName()) {
case DOUBLE:
type = Types.withMode(MinorType.FLOAT8, mode);
originalValue = literalValue.doubleValue();
break;
case FLOAT:
type = Types.withMode(MinorType.FLOAT4, mode);
originalValue = literalValue.floatValue();
break;
case DECIMAL:
type = Types.withPrecisionAndScale(MinorType.VARDECIMAL, mode, literalValue.precision(), literalValue.scale());
originalValue = literalValue;
break;
case BIGINT:
type = Types.withMode(MinorType.BIGINT, mode);
originalValue = literalValue.longValue();
break;
case INTEGER:
type = Types.withMode(MinorType.INT, mode);
originalValue = literalValue.intValue();
arraySegment = true;
break;
case SMALLINT:
type = Types.withMode(MinorType.SMALLINT, mode);
originalValue = literalValue.shortValue();
arraySegment = true;
break;
case TINYINT:
type = Types.withMode(MinorType.TINYINT, mode);
originalValue = literalValue.byteValue();
arraySegment = true;
break;
default:
throw new AssertionError("Shouldn't reach there. Type: " + mapType.getKeyType().getSqlTypeName());
}
if (arraySegment) {
return parentPath.getChild((int) originalValue, originalValue, type);
} else {
return parentPath.getChild(originalValue.toString(), originalValue, type);
}
}
private SchemaPath handleMapCharKey(RexLiteral literal, RexNode operand, RelDataType mapType, SchemaPath parentPath) {
TypeProtos.DataMode mode = operand.getType().isNullable()
? TypeProtos.DataMode.OPTIONAL : TypeProtos.DataMode.REQUIRED;
TypeProtos.MajorType type;
Object value = literal.getValue2();
switch (mapType.getKeyType().getSqlTypeName()) {
case TIMESTAMP:
type = Types.withMode(MinorType.TIMESTAMP, mode);
value = literal.getValueAs(TimestampString.class);
break;
case DATE:
type = Types.withMode(MinorType.DATE, mode);
value = literal.getValueAs(DateString.class);
break;
case TIME:
type = Types.withMode(MinorType.TIME, mode);
value = literal.getValueAs(TimeString.class);
break;
case INTERVAL_DAY:
type = Types.withMode(MinorType.INTERVALDAY, mode);
break;
case INTERVAL_YEAR:
type = Types.withMode(MinorType.INTERVALYEAR, mode);
break;
case INTERVAL_MONTH:
type = Types.withMode(MinorType.INTERVAL, mode);
break;
default:
type = Types.withMode(MinorType.VARCHAR, mode);
break;
}
return parentPath.getChild(value.toString(), value, type);
}
private LogicalExpression doFunction(RexCall call, String funcName) {
List<LogicalExpression> args = new ArrayList<>();
for(RexNode r : call.getOperands()){
args.add(r.accept(this));
}
if (FunctionCallFactory.isBooleanOperator(funcName)) {
LogicalExpression func = FunctionCallFactory.createBooleanOperator(funcName, args);
return func;
} else {
args = Lists.reverse(args);
LogicalExpression lastArg = args.get(0);
for(int i = 1; i < args.size(); i++){
lastArg = FunctionCallFactory.createExpression(funcName, Lists.newArrayList(args.get(i), lastArg));
}
return lastArg;
}
}
private LogicalExpression doUnknown(RexNode o){
// raise an error
throw UserException.planError().message(UNSUPPORTED_REX_NODE_ERROR +
"RexNode Class: %s, RexNode Digest: %s", o.getClass().getName(), o.toString()).build(logger);
}
@Override
public LogicalExpression visitLocalRef(RexLocalRef localRef) {
return doUnknown(localRef);
}
@Override
public LogicalExpression visitOver(RexOver over) {
return doUnknown(over);
}
@Override
public LogicalExpression visitCorrelVariable(RexCorrelVariable correlVariable) {
return doUnknown(correlVariable);
}
@Override
public LogicalExpression visitDynamicParam(RexDynamicParam dynamicParam) {
return doUnknown(dynamicParam);
}
@Override
public LogicalExpression visitRangeRef(RexRangeRef rangeRef) {
return doUnknown(rangeRef);
}
@Override
public LogicalExpression visitFieldAccess(RexFieldAccess fieldAccess) {
SchemaPath logicalRef = (SchemaPath) fieldAccess.getReferenceExpr().accept(this);
return logicalRef.getChild(fieldAccess.getField().getName());
}
private LogicalExpression getDrillCastFunctionFromOptiq(RexCall call){
LogicalExpression arg = call.getOperands().get(0).accept(this);
MajorType castType;
switch (call.getType().getSqlTypeName()) {
case VARCHAR:
case CHAR:
castType = Types.required(MinorType.VARCHAR).toBuilder().setPrecision(call.getType().getPrecision()).build();
break;
case INTEGER:
castType = Types.required(MinorType.INT);
break;
case FLOAT:
castType = Types.required(MinorType.FLOAT4);
break;
case DOUBLE:
castType = Types.required(MinorType.FLOAT8);
break;
case DECIMAL:
if (!context.getPlannerSettings().getOptions().getOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE)) {
throw UserException.unsupportedError()
.message(ExecErrorConstants.DECIMAL_DISABLE_ERR_MSG)
.build(logger);
}
int precision = call.getType().getPrecision();
int scale = call.getType().getScale();
castType = TypeProtos.MajorType.newBuilder()
.setMinorType(MinorType.VARDECIMAL)
.setPrecision(precision)
.setScale(scale)
.build();
break;
case INTERVAL_YEAR:
case INTERVAL_YEAR_MONTH:
case INTERVAL_MONTH:
castType = Types.required(MinorType.INTERVALYEAR);
break;
case INTERVAL_DAY:
case INTERVAL_DAY_HOUR:
case INTERVAL_DAY_MINUTE:
case INTERVAL_DAY_SECOND:
case INTERVAL_HOUR:
case INTERVAL_HOUR_MINUTE:
case INTERVAL_HOUR_SECOND:
case INTERVAL_MINUTE:
case INTERVAL_MINUTE_SECOND:
case INTERVAL_SECOND:
castType = Types.required(MinorType.INTERVALDAY);
break;
case BOOLEAN:
castType = Types.required(MinorType.BIT);
break;
case BINARY:
castType = Types.required(MinorType.VARBINARY);
break;
case ANY:
return arg; // Type will be same as argument.
default:
castType = Types.required(MinorType.valueOf(call.getType().getSqlTypeName().getName()));
}
return FunctionCallFactory.createCast(castType, ExpressionPosition.UNKNOWN, arg);
}
private LogicalExpression getDrillFunctionFromOptiqCall(RexCall call) {
List<LogicalExpression> args = new ArrayList<>();
for(RexNode n : call.getOperands()){
args.add(n.accept(this));
}
int argsSize = args.size();
String functionName = call.getOperator().getName().toLowerCase();
// TODO: once we have more function rewrites and a patter emerges from different rewrites, factor this out in a better fashion
/* Rewrite extract functions in the following manner
* extract(year, date '2008-2-23') ---> extractYear(date '2008-2-23')
*/
switch (functionName) {
case "extract": {
// Assert that the first argument to extract is a QuotedString
assert args.get(0) instanceof ValueExpressions.QuotedString;
// Get the unit of time to be extracted
String timeUnitStr = ((ValueExpressions.QuotedString) args.get(0)).value;
TimeUnit timeUnit;
// Clean up day of XXX
if (timeUnitStr.contentEquals("DAYOFWEEK")) {
timeUnit = TimeUnit.DOW;
} else if (timeUnitStr.contentEquals("DAYOFYEAR")) {
timeUnit = TimeUnit.DOY;
} else {
timeUnit = TimeUnit.valueOf(timeUnitStr);
}
switch (timeUnit) {
case YEAR:
case QUARTER:
case MONTH:
case WEEK:
case DAY:
case DOW:
case DOY:
case EPOCH:
case HOUR:
case MINUTE:
case SECOND:
String functionPostfix = StringUtils.capitalize(timeUnitStr.toLowerCase());
functionName += functionPostfix;
return FunctionCallFactory.createExpression(functionName, args.subList(1, 2));
default:
throw new UnsupportedOperationException("extract function supports the following " +
"time units: YEAR, QUARTER, MONTH, WEEK, DAY, DAYOFWEEK, DAYOFYEAR, EPOCH, HOUR, " +
"MINUTE, SECOND");
}
}
case "timestampdiff": {
// Assert that the first argument to extract is a QuotedString
Preconditions.checkArgument(args.get(0) instanceof ValueExpressions.QuotedString,
"The first argument of TIMESTAMPDIFF function should be QuotedString");
String timeUnitStr = ((ValueExpressions.QuotedString) args.get(0)).value;
TimeUnit timeUnit = TimeUnit.valueOf(timeUnitStr);
switch (timeUnit) {
case YEAR:
case MONTH:
case DAY:
case HOUR:
case MINUTE:
case SECOND:
case MILLISECOND:
case QUARTER:
case WEEK:
case MICROSECOND:
case NANOSECOND:
String functionPostfix = StringUtils.capitalize(timeUnitStr.toLowerCase());
functionName += functionPostfix;
return FunctionCallFactory.createExpression(functionName, args.subList(1, 3));
default:
throw new UnsupportedOperationException("TIMESTAMPDIFF function supports the following time units: " +
"YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, QUARTER, WEEK, MICROSECOND, NANOSECOND");
}
}
case "trim": {
String trimFunc;
List<LogicalExpression> trimArgs = new ArrayList<>();
assert args.get(0) instanceof ValueExpressions.QuotedString;
switch (((ValueExpressions.QuotedString) args.get(0)).value.toUpperCase()) {
case "LEADING":
trimFunc = "ltrim";
break;
case "TRAILING":
trimFunc = "rtrim";
break;
case "BOTH":
trimFunc = "btrim";
break;
default:
throw new UnsupportedOperationException("Invalid argument for TRIM function. " +
"Expected one of the following: LEADING, TRAILING, BOTH");
}
trimArgs.add(args.get(2));
trimArgs.add(args.get(1));
return FunctionCallFactory.createExpression(trimFunc, trimArgs);
}
case "date_part": {
// Rewrite DATE_PART functions as extract functions
// assert that the function has exactly two arguments
assert argsSize == 2;
/* Based on the first input to the date_part function we rewrite the function as the
* appropriate extract function. For example
* date_part('year', date '2008-2-23') ------> extractYear(date '2008-2-23')
*/
assert args.get(0) instanceof QuotedString;
QuotedString extractString = (QuotedString) args.get(0);
String functionPostfix = StringUtils.capitalize(extractString.value.toLowerCase());
return FunctionCallFactory.createExpression("extract" + functionPostfix, args.subList(1, 2));
}
case "concat": {
if (argsSize == 1) {
/*
* We treat concat with one argument as a special case. Since we don't have a function
* implementation of concat that accepts one argument. We simply add another dummy argument
* (empty string literal) to the list of arguments.
*/
List<LogicalExpression> concatArgs = new LinkedList<>(args);
concatArgs.add(QuotedString.EMPTY_STRING);
return FunctionCallFactory.createExpression(functionName, concatArgs);
} else if (argsSize > 2) {
List<LogicalExpression> concatArgs = new ArrayList<>();
/* stack concat functions on top of each other if we have more than two arguments
* Eg: concat(col1, col2, col3) => concat(concat(col1, col2), col3)
*/
concatArgs.add(args.get(0));
concatArgs.add(args.get(1));
LogicalExpression first = FunctionCallFactory.createExpression(functionName, concatArgs);
for (int i = 2; i < argsSize; i++) {
concatArgs = new ArrayList<>();
concatArgs.add(first);
concatArgs.add(args.get(i));
first = FunctionCallFactory.createExpression(functionName, concatArgs);
}
return first;
}
break;
}
case "length": {
if (argsSize == 2) {
// Second argument should always be a literal specifying the encoding format
assert args.get(1) instanceof ValueExpressions.QuotedString;
String encodingType = ((ValueExpressions.QuotedString) args.get(1)).value;
functionName += StringUtils.capitalize(encodingType.toLowerCase());
return FunctionCallFactory.createExpression(functionName, args.subList(0, 1));
}
break;
}
case "convert_from":
case "convert_to": {
if (args.get(1) instanceof QuotedString) {
return FunctionCallFactory.createConvert(functionName, ((QuotedString) args.get(1)).value, args.get(0), ExpressionPosition.UNKNOWN);
}
break;
}
case "date_trunc": {
return handleDateTruncFunction(args);
}
case "httprequest":
case "http_request": {
// This code resolves aliases in the http_request function.
String completeRawPluginName = ((QuotedString) args.get(0)).value;
String username = context.getPlannerSettings().getQueryUser();
AliasRegistryProvider aliasRegistryProvider = context.getPlannerSettings().getAliasRegistryProvider();
AliasRegistry storageAliasRegistry = aliasRegistryProvider.getStorageAliasesRegistry();
AliasRegistry tableAliasRegistry = aliasRegistryProvider.getTableAliasesRegistry();
// Split into plugin and endpoint
SchemaPath schemaPath = SchemaPath.parseFromString(completeRawPluginName);
String rawPluginName = SchemaPath.getSimplePath(schemaPath.rootName()).toExpr();
String rawEndpoint = SchemaPath.getSimplePath(schemaPath.getLastSegment().getNameSegment().getPath()).toExpr();
// Now resolve plugin name
String actualPluginName = storageAliasRegistry.getUserAliases(username).get(rawPluginName);
if (StringUtils.isEmpty(actualPluginName)) {
// If it is empty, assign it the original name,
actualPluginName = rawPluginName;
}
// Finally remove backticks
actualPluginName = SchemaPath.parseFromString(actualPluginName).getRootSegmentPath();
// Now do the same for the endpoint name
String actualEndpointName = tableAliasRegistry.getUserAliases(username).get(rawEndpoint);
if (StringUtils.isEmpty(actualEndpointName)) {
// If it is empty, assign it the original name,
actualEndpointName = rawEndpoint;
}
// Now remove backticks
actualEndpointName = SchemaPath.parseFromString(actualEndpointName).getRootSegmentPath();
String finalPluginName = SchemaPath
.getCompoundPath(actualPluginName, actualEndpointName)
.getAsUnescapedPath();
QuotedString q = new QuotedString(finalPluginName, finalPluginName.length(), ExpressionPosition.UNKNOWN);
// Add args to new arg lists
List<LogicalExpression> requestArgs = new ArrayList<>();
requestArgs.add(q);
requestArgs.addAll(args.subList(1, args.size()));
return FunctionCallFactory.createExpression(functionName, requestArgs);
}
}
return FunctionCallFactory.createExpression(functionName, args);
}
private LogicalExpression handleDateTruncFunction(final List<LogicalExpression> args) {
// Assert that the first argument to extract is a QuotedString
assert args.get(0) instanceof ValueExpressions.QuotedString;
// Get the unit of time to be extracted
String timeUnitStr = ((ValueExpressions.QuotedString) args.get(0)).value.toUpperCase();
TimeUnit timeUnit = TimeUnit.valueOf(timeUnitStr);
switch (timeUnit) {
case YEAR:
case MONTH:
case DAY:
case HOUR:
case MINUTE:
case SECOND:
case WEEK:
case QUARTER:
case DECADE:
case CENTURY:
case MILLENNIUM:
final String functionPostfix = StringUtils.capitalize(timeUnitStr.toLowerCase());
return FunctionCallFactory.createExpression("date_trunc_" + functionPostfix, args.subList(1, 2));
default:
throw new UnsupportedOperationException("date_trunc function supports the following time units: " +
"YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, WEEK, QUARTER, DECADE, CENTURY, MILLENNIUM");
}
}
@Override
public LogicalExpression visitLiteral(RexLiteral literal) {
switch(literal.getType().getSqlTypeName()){
case BIGINT:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.BIGINT);
}
long l = (((BigDecimal) literal.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)).longValue();
return ValueExpressions.getBigInt(l);
case BOOLEAN:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.BIT);
}
return ValueExpressions.getBit(((Boolean) literal.getValue()));
case CHAR:
if (isLiteralNull(literal)) {
return createStringNullExpr(literal.getType().getPrecision());
}
return ValueExpressions.getChar(((NlsString)literal.getValue()).getValue(), literal.getType().getPrecision());
case DOUBLE:
if (isLiteralNull(literal)){
return createNullExpr(MinorType.FLOAT8);
}
double d = ((BigDecimal) literal.getValue()).doubleValue();
return ValueExpressions.getFloat8(d);
case FLOAT:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.FLOAT4);
}
float f = ((BigDecimal) literal.getValue()).floatValue();
return ValueExpressions.getFloat4(f);
case INTEGER:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.INT);
}
int a = (((BigDecimal) literal.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)).intValue();
return ValueExpressions.getInt(a);
case DECIMAL:
if (context.getPlannerSettings().getOptions()
.getBoolean(ENABLE_DECIMAL_DATA_TYPE.getOptionName())) {
if (isLiteralNull(literal)) {
return new TypedNullConstant(
Types.withPrecisionAndScale(
MinorType.VARDECIMAL,
TypeProtos.DataMode.OPTIONAL,
literal.getType().getPrecision(),
literal.getType().getScale()
));
}
return ValueExpressions.getVarDecimal((BigDecimal) literal.getValue(),
literal.getType().getPrecision(),
literal.getType().getScale());
}
double dbl = ((BigDecimal) literal.getValue()).doubleValue();
logger.warn("Converting exact decimal into approximate decimal.\n" +
"Please enable decimal data types using `planner.enable_decimal_data_type`.");
return ValueExpressions.getFloat8(dbl);
case VARCHAR:
if (isLiteralNull(literal)) {
return createStringNullExpr(literal.getType().getPrecision());
}
return ValueExpressions.getChar(((NlsString)literal.getValue()).getValue(), literal.getType().getPrecision());
case SYMBOL:
if (isLiteralNull(literal)) {
return createStringNullExpr(literal.getType().getPrecision());
}
return ValueExpressions.getChar(literal.getValue().toString(), literal.getType().getPrecision());
case DATE:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.DATE);
}
return (ValueExpressions.getDate((GregorianCalendar)literal.getValue()));
case TIME:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.TIME);
}
return (ValueExpressions.getTime((GregorianCalendar)literal.getValue()));
case TIMESTAMP:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.TIMESTAMP);
}
return (ValueExpressions.getTimeStamp((GregorianCalendar) literal.getValue()));
case INTERVAL_YEAR_MONTH:
case INTERVAL_YEAR:
case INTERVAL_MONTH:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.INTERVALYEAR);
}
return (ValueExpressions.getIntervalYear(((BigDecimal) (literal.getValue())).intValue()));
case INTERVAL_DAY:
case INTERVAL_DAY_HOUR:
case INTERVAL_DAY_MINUTE:
case INTERVAL_DAY_SECOND:
case INTERVAL_HOUR:
case INTERVAL_HOUR_MINUTE:
case INTERVAL_HOUR_SECOND:
case INTERVAL_MINUTE:
case INTERVAL_MINUTE_SECOND:
case INTERVAL_SECOND:
if (isLiteralNull(literal)) {
return createNullExpr(MinorType.INTERVALDAY);
}
return (ValueExpressions.getIntervalDay(((BigDecimal) (literal.getValue())).longValue()));
case NULL:
return NullExpression.INSTANCE;
case ANY:
if (isLiteralNull(literal)) {
return NullExpression.INSTANCE;
}
default:
throw new UnsupportedOperationException(String.format("Unable to convert the value of %s and type %s to a Drill constant expression.", literal, literal.getType().getSqlTypeName()));
}
}
/**
* Create nullable major type using given minor type
* and wraps it in typed null constant.
*
* @param type minor type
* @return typed null constant instance
*/
private TypedNullConstant createNullExpr(MinorType type) {
return new TypedNullConstant(Types.optional(type));
}
/**
* Create nullable varchar major type with given precision
* and wraps it in typed null constant.
*
* @param precision precision value
* @return typed null constant instance
*/
private TypedNullConstant createStringNullExpr(int precision) {
return new TypedNullConstant(Types.withPrecision(MinorType.VARCHAR, TypeProtos.DataMode.OPTIONAL, precision));
}
}
public static boolean isLiteralNull(RexLiteral literal) {
return literal.getTypeName().getName().equals("NULL");
}
}
|
googleapis/google-cloud-java | 37,985 | java-shopping-merchant-promotions/proto-google-shopping-merchant-promotions-v1beta/src/main/java/com/google/shopping/merchant/promotions/v1beta/InsertPromotionRequest.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/promotions/v1beta/promotions.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.promotions.v1beta;
/**
*
*
* <pre>
* Request message for the `InsertPromotion` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.promotions.v1beta.InsertPromotionRequest}
*/
public final class InsertPromotionRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.promotions.v1beta.InsertPromotionRequest)
InsertPromotionRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use InsertPromotionRequest.newBuilder() to construct.
private InsertPromotionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InsertPromotionRequest() {
parent_ = "";
dataSource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new InsertPromotionRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.promotions.v1beta.PromotionsProto
.internal_static_google_shopping_merchant_promotions_v1beta_InsertPromotionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.promotions.v1beta.PromotionsProto
.internal_static_google_shopping_merchant_promotions_v1beta_InsertPromotionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest.class,
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROMOTION_FIELD_NUMBER = 2;
private com.google.shopping.merchant.promotions.v1beta.Promotion promotion_;
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the promotion field is set.
*/
@java.lang.Override
public boolean hasPromotion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The promotion.
*/
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.Promotion getPromotion() {
return promotion_ == null
? com.google.shopping.merchant.promotions.v1beta.Promotion.getDefaultInstance()
: promotion_;
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.PromotionOrBuilder getPromotionOrBuilder() {
return promotion_ == null
? com.google.shopping.merchant.promotions.v1beta.Promotion.getDefaultInstance()
: promotion_;
}
public static final int DATA_SOURCE_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object dataSource_ = "";
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The dataSource.
*/
@java.lang.Override
public java.lang.String getDataSource() {
java.lang.Object ref = dataSource_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
dataSource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for dataSource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDataSourceBytes() {
java.lang.Object ref = dataSource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
dataSource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getPromotion());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(dataSource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, dataSource_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getPromotion());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(dataSource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, dataSource_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest)) {
return super.equals(obj);
}
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest other =
(com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasPromotion() != other.hasPromotion()) return false;
if (hasPromotion()) {
if (!getPromotion().equals(other.getPromotion())) return false;
}
if (!getDataSource().equals(other.getDataSource())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
if (hasPromotion()) {
hash = (37 * hash) + PROMOTION_FIELD_NUMBER;
hash = (53 * hash) + getPromotion().hashCode();
}
hash = (37 * hash) + DATA_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getDataSource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest 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.promotions.v1beta.InsertPromotionRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest 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.promotions.v1beta.InsertPromotionRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest 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.promotions.v1beta.InsertPromotionRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
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.promotions.v1beta.InsertPromotionRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest 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.promotions.v1beta.InsertPromotionRequest 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 `InsertPromotion` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.promotions.v1beta.InsertPromotionRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.promotions.v1beta.InsertPromotionRequest)
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.promotions.v1beta.PromotionsProto
.internal_static_google_shopping_merchant_promotions_v1beta_InsertPromotionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.promotions.v1beta.PromotionsProto
.internal_static_google_shopping_merchant_promotions_v1beta_InsertPromotionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest.class,
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest.Builder.class);
}
// Construct using
// com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPromotionFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
promotion_ = null;
if (promotionBuilder_ != null) {
promotionBuilder_.dispose();
promotionBuilder_ = null;
}
dataSource_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.promotions.v1beta.PromotionsProto
.internal_static_google_shopping_merchant_promotions_v1beta_InsertPromotionRequest_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
getDefaultInstanceForType() {
return com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest build() {
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest buildPartial() {
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest result =
new com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.promotion_ = promotionBuilder_ == null ? promotion_ : promotionBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.dataSource_ = dataSource_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest) {
return mergeFrom(
(com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest other) {
if (other
== com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasPromotion()) {
mergePromotion(other.getPromotion());
}
if (!other.getDataSource().isEmpty()) {
dataSource_ = other.dataSource_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getPromotionFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
dataSource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The account where the promotion will be inserted.
* Format: accounts/{account}
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.shopping.merchant.promotions.v1beta.Promotion promotion_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.promotions.v1beta.Promotion,
com.google.shopping.merchant.promotions.v1beta.Promotion.Builder,
com.google.shopping.merchant.promotions.v1beta.PromotionOrBuilder>
promotionBuilder_;
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the promotion field is set.
*/
public boolean hasPromotion() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The promotion.
*/
public com.google.shopping.merchant.promotions.v1beta.Promotion getPromotion() {
if (promotionBuilder_ == null) {
return promotion_ == null
? com.google.shopping.merchant.promotions.v1beta.Promotion.getDefaultInstance()
: promotion_;
} else {
return promotionBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setPromotion(com.google.shopping.merchant.promotions.v1beta.Promotion value) {
if (promotionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
promotion_ = value;
} else {
promotionBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setPromotion(
com.google.shopping.merchant.promotions.v1beta.Promotion.Builder builderForValue) {
if (promotionBuilder_ == null) {
promotion_ = builderForValue.build();
} else {
promotionBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergePromotion(com.google.shopping.merchant.promotions.v1beta.Promotion value) {
if (promotionBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& promotion_ != null
&& promotion_
!= com.google.shopping.merchant.promotions.v1beta.Promotion.getDefaultInstance()) {
getPromotionBuilder().mergeFrom(value);
} else {
promotion_ = value;
}
} else {
promotionBuilder_.mergeFrom(value);
}
if (promotion_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearPromotion() {
bitField0_ = (bitField0_ & ~0x00000002);
promotion_ = null;
if (promotionBuilder_ != null) {
promotionBuilder_.dispose();
promotionBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.promotions.v1beta.Promotion.Builder getPromotionBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getPromotionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.promotions.v1beta.PromotionOrBuilder
getPromotionOrBuilder() {
if (promotionBuilder_ != null) {
return promotionBuilder_.getMessageOrBuilder();
} else {
return promotion_ == null
? com.google.shopping.merchant.promotions.v1beta.Promotion.getDefaultInstance()
: promotion_;
}
}
/**
*
*
* <pre>
* Required. The promotion to insert.
* </pre>
*
* <code>
* .google.shopping.merchant.promotions.v1beta.Promotion promotion = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.promotions.v1beta.Promotion,
com.google.shopping.merchant.promotions.v1beta.Promotion.Builder,
com.google.shopping.merchant.promotions.v1beta.PromotionOrBuilder>
getPromotionFieldBuilder() {
if (promotionBuilder_ == null) {
promotionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.promotions.v1beta.Promotion,
com.google.shopping.merchant.promotions.v1beta.Promotion.Builder,
com.google.shopping.merchant.promotions.v1beta.PromotionOrBuilder>(
getPromotion(), getParentForChildren(), isClean());
promotion_ = null;
}
return promotionBuilder_;
}
private java.lang.Object dataSource_ = "";
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The dataSource.
*/
public java.lang.String getDataSource() {
java.lang.Object ref = dataSource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
dataSource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for dataSource.
*/
public com.google.protobuf.ByteString getDataSourceBytes() {
java.lang.Object ref = dataSource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
dataSource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The dataSource to set.
* @return This builder for chaining.
*/
public Builder setDataSource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
dataSource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearDataSource() {
dataSource_ = getDefaultInstance().getDataSource();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The data source of the
* [promotion](https://support.google.com/merchants/answer/6396268?sjid=5155774230887277618-NC)
* Format:
* `accounts/{account}/dataSources/{datasource}`.
* </pre>
*
* <code>string data_source = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for dataSource to set.
* @return This builder for chaining.
*/
public Builder setDataSourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
dataSource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.shopping.merchant.promotions.v1beta.InsertPromotionRequest)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.promotions.v1beta.InsertPromotionRequest)
private static final com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest();
}
public static com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InsertPromotionRequest> PARSER =
new com.google.protobuf.AbstractParser<InsertPromotionRequest>() {
@java.lang.Override
public InsertPromotionRequest 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<InsertPromotionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InsertPromotionRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.promotions.v1beta.InsertPromotionRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 38,150 | jdk/src/share/classes/com/sun/jndi/ldap/Connection.java | /*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jndi.ldap;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.Socket;
import javax.net.ssl.SSLSocket;
import javax.naming.CommunicationException;
import javax.naming.ServiceUnavailableException;
import javax.naming.NamingException;
import javax.naming.InterruptedNamingException;
import javax.naming.ldap.Control;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import sun.misc.IOUtils;
//import javax.net.SocketFactory;
/**
* A thread that creates a connection to an LDAP server.
* After the connection, the thread reads from the connection.
* A caller can invoke methods on the instance to read LDAP responses
* and to send LDAP requests.
* <p>
* There is a one-to-one correspondence between an LdapClient and
* a Connection. Access to Connection and its methods is only via
* LdapClient with two exceptions: SASL authentication and StartTLS.
* SASL needs to access Connection's socket IO streams (in order to do encryption
* of the security layer). StartTLS needs to do replace IO streams
* and close the IO streams on nonfatal close. The code for SASL
* authentication can be treated as being the same as from LdapClient
* because the SASL code is only ever called from LdapClient, from
* inside LdapClient's synchronized authenticate() method. StartTLS is called
* directly by the application but should only occur when the underlying
* connection is quiet.
* <p>
* In terms of synchronization, worry about data structures
* used by the Connection thread because that usage might contend
* with calls by the main threads (i.e., those that call LdapClient).
* Main threads need to worry about contention with each other.
* Fields that Connection thread uses:
* inStream - synced access and update; initialized in constructor;
* referenced outside class unsync'ed (by LdapSasl) only
* when connection is quiet
* traceFile, traceTagIn, traceTagOut - no sync; debugging only
* parent - no sync; initialized in constructor; no updates
* pendingRequests - sync
* pauseLock - per-instance lock;
* paused - sync via pauseLock (pauseReader())
* Members used by main threads (LdapClient):
* host, port - unsync; read-only access for StartTLS and debug messages
* setBound(), setV3() - no sync; called only by LdapClient.authenticate(),
* which is a sync method called only when connection is "quiet"
* getMsgId() - sync
* writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -
* access to shared pendingRequests is sync
* writeRequest(), abandonRequest(), ldapUnbind() - access to outStream sync
* cleanup() - sync
* readReply() - access to sock sync
* unpauseReader() - (indirectly via writeRequest) sync on pauseLock
* Members used by SASL auth (main thread):
* inStream, outStream - no sync; used to construct new stream; accessed
* only when conn is "quiet" and not shared
* replaceStreams() - sync method
* Members used by StartTLS:
* inStream, outStream - no sync; used to record the existing streams;
* accessed only when conn is "quiet" and not shared
* replaceStreams() - sync method
* <p>
* Handles anonymous, simple, and SASL bind for v3; anonymous and simple
* for v2.
* %%% made public for access by LdapSasl %%%
*
* @author Vincent Ryan
* @author Rosanna Lee
* @author Jagane Sundar
*/
public final class Connection implements Runnable {
private static final boolean debug = false;
private static final int dump = 0; // > 0 r, > 1 rw
final private Thread worker; // Initialized in constructor
private boolean v3 = true; // Set in setV3()
final public String host; // used by LdapClient for generating exception messages
// used by StartTlsResponse when creating an SSL socket
final public int port; // used by LdapClient for generating exception messages
// used by StartTlsResponse when creating an SSL socket
private boolean bound = false; // Set in setBound()
// All three are initialized in constructor and read-only afterwards
private OutputStream traceFile = null;
private String traceTagIn = null;
private String traceTagOut = null;
// Initialized in constructor; read and used externally (LdapSasl);
// Updated in replaceStreams() during "quiet", unshared, period
public InputStream inStream; // must be public; used by LdapSasl
// Initialized in constructor; read and used externally (LdapSasl);
// Updated in replaceOutputStream() during "quiet", unshared, period
public OutputStream outStream; // must be public; used by LdapSasl
// Initialized in constructor; read and used externally (TLS) to
// get new IO streams; closed during cleanup
public Socket sock; // for TLS
// For processing "disconnect" unsolicited notification
// Initialized in constructor
final private LdapClient parent;
// Incremented and returned in sync getMsgId()
private int outMsgId = 0;
//
// The list of ldapRequests pending on this binding
//
// Accessed only within sync methods
private LdapRequest pendingRequests = null;
volatile IOException closureReason = null;
volatile boolean useable = true; // is Connection still useable
int readTimeout;
int connectTimeout;
// true means v3; false means v2
// Called in LdapClient.authenticate() (which is synchronized)
// when connection is "quiet" and not shared; no need to synchronize
void setV3(boolean v) {
v3 = v;
}
// A BIND request has been successfully made on this connection
// When cleaning up, remember to do an UNBIND
// Called in LdapClient.authenticate() (which is synchronized)
// when connection is "quiet" and not shared; no need to synchronize
void setBound() {
bound = true;
}
////////////////////////////////////////////////////////////////////////////
//
// Create an LDAP Binding object and bind to a particular server
//
////////////////////////////////////////////////////////////////////////////
Connection(LdapClient parent, String host, int port, String socketFactory,
int connectTimeout, int readTimeout, OutputStream trace) throws NamingException {
this.host = host;
this.port = port;
this.parent = parent;
this.readTimeout = readTimeout;
this.connectTimeout = connectTimeout;
if (trace != null) {
traceFile = trace;
traceTagIn = "<- " + host + ":" + port + "\n\n";
traceTagOut = "-> " + host + ":" + port + "\n\n";
}
//
// Connect to server
//
try {
sock = createSocket(host, port, socketFactory, connectTimeout);
if (debug) {
System.err.println("Connection: opening socket: " + host + "," + port);
}
inStream = new BufferedInputStream(sock.getInputStream());
outStream = new BufferedOutputStream(sock.getOutputStream());
} catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
// realException.printStackTrace();
CommunicationException ce =
new CommunicationException(host + ":" + port);
ce.setRootCause(realException);
throw ce;
} catch (Exception e) {
// Class.forName() seems to do more error checking
// and will throw IllegalArgumentException and such.
// That's why we need to have a catch all here and
// ignore generic exceptions.
// Also catches all IO errors generated by socket creation.
CommunicationException ce =
new CommunicationException(host + ":" + port);
ce.setRootCause(e);
throw ce;
}
worker = Obj.helper.createThread(this);
worker.setDaemon(true);
worker.start();
}
/*
* Create an InetSocketAddress using the specified hostname and port number.
*/
private Object createInetSocketAddress(String host, int port)
throws NoSuchMethodException {
try {
Class<?> inetSocketAddressClass =
Class.forName("java.net.InetSocketAddress");
Constructor<?> inetSocketAddressCons =
inetSocketAddressClass.getConstructor(new Class<?>[]{
String.class, int.class});
return inetSocketAddressCons.newInstance(new Object[]{
host, new Integer(port)});
} catch (ClassNotFoundException |
InstantiationException |
InvocationTargetException |
IllegalAccessException e) {
throw new NoSuchMethodException();
}
}
/*
* Create a Socket object using the specified socket factory and time limit.
*
* If a timeout is supplied and unconnected sockets are supported then
* an unconnected socket is created and the timeout is applied when
* connecting the socket. If a timeout is supplied but unconnected sockets
* are not supported then the timeout is ignored and a connected socket
* is created.
*/
private Socket createSocket(String host, int port, String socketFactory,
int connectTimeout) throws Exception {
Socket socket = null;
if (socketFactory != null) {
// create the factory
Class<?> socketFactoryClass = Obj.helper.loadClass(socketFactory);
Method getDefault =
socketFactoryClass.getMethod("getDefault", new Class<?>[]{});
Object factory = getDefault.invoke(null, new Object[]{});
// create the socket
Method createSocket = null;
if (connectTimeout > 0) {
try {
createSocket = socketFactoryClass.getMethod("createSocket",
new Class<?>[]{});
Method connect = Socket.class.getMethod("connect",
new Class<?>[]{Class.forName("java.net.SocketAddress"),
int.class});
Object endpoint = createInetSocketAddress(host, port);
// unconnected socket
socket =
(Socket)createSocket.invoke(factory, new Object[]{});
if (debug) {
System.err.println("Connection: creating socket with " +
"a timeout using supplied socket factory");
}
// connected socket
connect.invoke(socket, new Object[]{
endpoint, new Integer(connectTimeout)});
} catch (NoSuchMethodException e) {
// continue (but ignore connectTimeout)
}
}
if (socket == null) {
createSocket = socketFactoryClass.getMethod("createSocket",
new Class<?>[]{String.class, int.class});
if (debug) {
System.err.println("Connection: creating socket using " +
"supplied socket factory");
}
// connected socket
socket = (Socket) createSocket.invoke(factory,
new Object[]{host, new Integer(port)});
}
} else {
if (connectTimeout > 0) {
try {
Constructor<Socket> socketCons =
Socket.class.getConstructor(new Class<?>[]{});
Method connect = Socket.class.getMethod("connect",
new Class<?>[]{Class.forName("java.net.SocketAddress"),
int.class});
Object endpoint = createInetSocketAddress(host, port);
socket = socketCons.newInstance(new Object[]{});
if (debug) {
System.err.println("Connection: creating socket with " +
"a timeout");
}
connect.invoke(socket, new Object[]{
endpoint, new Integer(connectTimeout)});
} catch (NoSuchMethodException e) {
// continue (but ignore connectTimeout)
}
}
if (socket == null) {
if (debug) {
System.err.println("Connection: creating socket");
}
// connected socket
socket = new Socket(host, port);
}
}
// For LDAP connect timeouts on LDAP over SSL connections must treat
// the SSL handshake following socket connection as part of the timeout.
// So explicitly set a socket read timeout, trigger the SSL handshake,
// then reset the timeout.
if (connectTimeout > 0 && socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
int socketTimeout = sslSocket.getSoTimeout();
sslSocket.setSoTimeout(connectTimeout); // reuse full timeout value
sslSocket.startHandshake();
sslSocket.setSoTimeout(socketTimeout);
}
return socket;
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to IO to the LDAP server
//
////////////////////////////////////////////////////////////////////////////
synchronized int getMsgId() {
return ++outMsgId;
}
LdapRequest writeRequest(BerEncoder ber, int msgId) throws IOException {
return writeRequest(ber, msgId, false /* pauseAfterReceipt */, -1);
}
LdapRequest writeRequest(BerEncoder ber, int msgId,
boolean pauseAfterReceipt) throws IOException {
return writeRequest(ber, msgId, pauseAfterReceipt, -1);
}
LdapRequest writeRequest(BerEncoder ber, int msgId,
boolean pauseAfterReceipt, int replyQueueCapacity) throws IOException {
LdapRequest req =
new LdapRequest(msgId, pauseAfterReceipt, replyQueueCapacity);
addRequest(req);
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0, ber.getDataLen());
}
// unpause reader so that it can get response
// NOTE: Must do this before writing request, otherwise might
// create a race condition where the writer unblocks its own response
unpauseReader();
if (debug) {
System.err.println("Writing request to: " + outStream);
}
try {
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException e) {
cleanup(null, true);
throw (closureReason = e); // rethrow
}
return req;
}
/**
* Reads a reply; waits until one is ready.
*/
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
try {
// If socket closed, don't even try
synchronized (this) {
if (sock == null) {
throw new ServiceUnavailableException(host + ":" + port +
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
ldr.wait(15 * 1000); // 15 second timeout
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
if ((rber == null) && waited) {
removeRequest(ldr);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to add, find, delete, and abandon requests made to server
//
////////////////////////////////////////////////////////////////////////////
private synchronized void addRequest(LdapRequest ldapRequest) {
LdapRequest ldr = pendingRequests;
if (ldr == null) {
pendingRequests = ldapRequest;
ldapRequest.next = null;
} else {
ldapRequest.next = pendingRequests;
pendingRequests = ldapRequest;
}
}
synchronized LdapRequest findRequest(int msgId) {
LdapRequest ldr = pendingRequests;
while (ldr != null) {
if (ldr.msgId == msgId) {
return ldr;
}
ldr = ldr.next;
}
return null;
}
synchronized void removeRequest(LdapRequest req) {
LdapRequest ldr = pendingRequests;
LdapRequest ldrprev = null;
while (ldr != null) {
if (ldr == req) {
ldr.cancel();
if (ldrprev != null) {
ldrprev.next = ldr.next;
} else {
pendingRequests = ldr.next;
}
ldr.next = null;
}
ldrprev = ldr;
ldr = ldr.next;
}
}
void abandonRequest(LdapRequest ldr, Control[] reqCtls) {
// Remove from queue
removeRequest(ldr);
BerEncoder ber = new BerEncoder(256);
int abandonMsgId = getMsgId();
//
// build the abandon request.
//
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(abandonMsgId);
ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);
if (v3) {
LdapClient.encodeControls(ber, reqCtls);
}
ber.endSeq();
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,
ber.getDataLen());
}
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException ex) {
//System.err.println("ldap.abandon: " + ex);
}
// Don't expect any response for the abandon request.
}
synchronized void abandonOutstandingReqs(Control[] reqCtls) {
LdapRequest ldr = pendingRequests;
while (ldr != null) {
abandonRequest(ldr, reqCtls);
pendingRequests = ldr = ldr.next;
}
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to unbind from server and clear up resources when object is
// destroyed.
//
////////////////////////////////////////////////////////////////////////////
private void ldapUnbind(Control[] reqCtls) {
BerEncoder ber = new BerEncoder(256);
int unbindMsgId = getMsgId();
//
// build the unbind request.
//
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(unbindMsgId);
// IMPLICIT TAGS
ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);
ber.encodeByte(0);
if (v3) {
LdapClient.encodeControls(ber, reqCtls);
}
ber.endSeq();
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
0, ber.getDataLen());
}
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException ex) {
//System.err.println("ldap.unbind: " + ex);
}
// Don't expect any response for the unbind request.
}
/**
* @param reqCtls Possibly null request controls that accompanies the
* abandon and unbind LDAP request.
* @param notifyParent true means to call parent LdapClient back, notifying
* it that the connection has been closed; false means not to notify
* parent. If LdapClient invokes cleanup(), notifyParent should be set to
* false because LdapClient already knows that it is closing
* the connection. If Connection invokes cleanup(), notifyParent should be
* set to true because LdapClient needs to know about the closure.
*/
void cleanup(Control[] reqCtls, boolean notifyParent) {
boolean nparent = false;
synchronized (this) {
useable = false;
if (sock != null) {
if (debug) {
System.err.println("Connection: closing socket: " + host + "," + port);
}
try {
if (!notifyParent) {
abandonOutstandingReqs(reqCtls);
}
if (bound) {
ldapUnbind(reqCtls);
}
} finally {
try {
outStream.flush();
sock.close();
unpauseReader();
} catch (IOException ie) {
if (debug)
System.err.println("Connection: problem closing socket: " + ie);
}
if (!notifyParent) {
LdapRequest ldr = pendingRequests;
while (ldr != null) {
ldr.cancel();
ldr = ldr.next;
}
}
sock = null;
}
nparent = notifyParent;
}
if (nparent) {
LdapRequest ldr = pendingRequests;
while (ldr != null) {
synchronized (ldr) {
ldr.notify();
ldr = ldr.next;
}
}
}
}
if (nparent) {
parent.processConnectionClosure();
}
}
// Assume everything is "quiet"
// "synchronize" might lead to deadlock so don't synchronize method
// Use streamLock instead for synchronizing update to stream
synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) {
if (debug) {
System.err.println("Replacing " + inStream + " with: " + newIn);
System.err.println("Replacing " + outStream + " with: " + newOut);
}
inStream = newIn;
// Cleanup old stream
try {
outStream.flush();
} catch (IOException ie) {
if (debug)
System.err.println("Connection: cannot flush outstream: " + ie);
}
// Replace stream
outStream = newOut;
}
/**
* Used by Connection thread to read inStream into a local variable.
* This ensures that there is no contention between the main thread
* and the Connection thread when the main thread updates inStream.
*/
synchronized private InputStream getInputStream() {
return inStream;
}
////////////////////////////////////////////////////////////////////////////
//
// Code for pausing/unpausing the reader thread ('worker')
//
////////////////////////////////////////////////////////////////////////////
/*
* The main idea is to mark requests that need the reader thread to
* pause after getting the response. When the reader thread gets the response,
* it waits on a lock instead of returning to the read(). The next time a
* request is sent, the reader is automatically unblocked if necessary.
* Note that the reader must be unblocked BEFORE the request is sent.
* Otherwise, there is a race condition where the request is sent and
* the reader thread might read the response and be unblocked
* by writeRequest().
*
* This pause gives the main thread (StartTLS or SASL) an opportunity to
* update the reader's state (e.g., its streams) if necessary.
* The assumption is that the connection will remain quiet during this pause
* (i.e., no intervening requests being sent).
*<p>
* For dealing with StartTLS close,
* when the read() exits either due to EOF or an exception,
* the reader thread checks whether there is a new stream to read from.
* If so, then it reattempts the read. Otherwise, the EOF or exception
* is processed and the reader thread terminates.
* In a StartTLS close, the client first replaces the SSL IO streams with
* plain ones and then closes the SSL socket.
* If the reader thread attempts to read, or was reading, from
* the SSL socket (that is, it got to the read BEFORE replaceStreams()),
* the SSL socket close will cause the reader thread to
* get an EOF/exception and reexamine the input stream.
* If the reader thread sees a new stream, it reattempts the read.
* If the underlying socket is still alive, then the new read will succeed.
* If the underlying socket has been closed also, then the new read will
* fail and the reader thread exits.
* If the reader thread attempts to read, or was reading, from the plain
* socket (that is, it got to the read AFTER replaceStreams()), the
* SSL socket close will have no effect on the reader thread.
*
* The check for new stream is made only
* in the first attempt at reading a BER buffer; the reader should
* never be in midst of reading a buffer when a nonfatal close occurs.
* If this occurs, then the connection is in an inconsistent state and
* the safest thing to do is to shut it down.
*/
private Object pauseLock = new Object(); // lock for reader to wait on while paused
private boolean paused = false; // paused state of reader
/*
* Unpauses reader thread if it was paused
*/
private void unpauseReader() throws IOException {
synchronized (pauseLock) {
if (paused) {
if (debug) {
System.err.println("Unpausing reader; read from: " +
inStream);
}
paused = false;
pauseLock.notify();
}
}
}
/*
* Pauses reader so that it stops reading from the input stream.
* Reader blocks on pauseLock instead of read().
* MUST be called from within synchronized (pauseLock) clause.
*/
private void pauseReader() throws IOException {
if (debug) {
System.err.println("Pausing reader; was reading from: " +
inStream);
}
paused = true;
try {
while (paused) {
pauseLock.wait(); // notified by unpauseReader
}
} catch (InterruptedException e) {
throw new InterruptedIOException(
"Pause/unpause reader has problems.");
}
}
////////////////////////////////////////////////////////////////////////////
//
// The LDAP Binding thread. It does the mux/demux of multiple requests
// on the same TCP connection.
//
////////////////////////////////////////////////////////////////////////////
public void run() {
byte inbuf[]; // Buffer for reading incoming bytes
int inMsgId; // Message id of incoming response
int bytesread; // Number of bytes in inbuf
int br; // Temp; number of bytes read from stream
int offset; // Offset of where to store bytes in inbuf
int seqlen; // Length of ASN sequence
int seqlenlen; // Number of sequence length bytes
boolean eos; // End of stream
BerDecoder retBer; // Decoder for ASN.1 BER data from inbuf
InputStream in = null;
try {
while (true) {
try {
// type and length (at most 128 octets for long form)
inbuf = new byte[129];
offset = 0;
seqlen = 0;
seqlenlen = 0;
in = getInputStream();
// check that it is the beginning of a sequence
bytesread = in.read(inbuf, offset, 1);
if (bytesread < 0) {
if (in != getInputStream()) {
continue; // a new stream to try
} else {
break; // EOF
}
}
if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))
continue;
// get length of sequence
bytesread = in.read(inbuf, offset, 1);
if (bytesread < 0)
break; // EOF
seqlen = inbuf[offset++];
// if high bit is on, length is encoded in the
// subsequent length bytes and the number of length bytes
// is equal to & 0x80 (i.e. length byte with high bit off).
if ((seqlen & 0x80) == 0x80) {
seqlenlen = seqlen & 0x7f; // number of length bytes
bytesread = 0;
eos = false;
// Read all length bytes
while (bytesread < seqlenlen) {
br = in.read(inbuf, offset+bytesread,
seqlenlen-bytesread);
if (br < 0) {
eos = true;
break; // EOF
}
bytesread += br;
}
// end-of-stream reached before length bytes are read
if (eos)
break; // EOF
// Add contents of length bytes to determine length
seqlen = 0;
for( int i = 0; i < seqlenlen; i++) {
seqlen = (seqlen << 8) + (inbuf[offset+i] & 0xff);
}
offset += bytesread;
}
// read in seqlen bytes
byte[] left = IOUtils.readFully(in, seqlen, false);
inbuf = Arrays.copyOf(inbuf, offset + left.length);
System.arraycopy(left, 0, inbuf, offset, left.length);
offset += left.length;
/*
if (dump > 0) {
System.err.println("seqlen: " + seqlen);
System.err.println("bufsize: " + offset);
System.err.println("bytesleft: " + bytesleft);
System.err.println("bytesread: " + bytesread);
}
*/
try {
retBer = new BerDecoder(inbuf, 0, offset);
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);
}
retBer.parseSeq(null);
inMsgId = retBer.parseInt();
retBer.reset(); // reset offset
boolean needPause = false;
if (inMsgId == 0) {
// Unsolicited Notification
parent.processUnsolicited(retBer);
} else {
LdapRequest ldr = findRequest(inMsgId);
if (ldr != null) {
/**
* Grab pauseLock before making reply available
* to ensure that reader goes into paused state
* before writer can attempt to unpause reader
*/
synchronized (pauseLock) {
needPause = ldr.addReplyBer(retBer);
if (needPause) {
/*
* Go into paused state; release
* pauseLock
*/
pauseReader();
}
// else release pauseLock
}
} else {
// System.err.println("Cannot find" +
// "LdapRequest for " + inMsgId);
}
}
} catch (Ber.DecodeException e) {
//System.err.println("Cannot parse Ber");
}
} catch (IOException ie) {
if (debug) {
System.err.println("Connection: Inside Caught " + ie);
ie.printStackTrace();
}
if (in != getInputStream()) {
// A new stream to try
// Go to top of loop and continue
} else {
if (debug) {
System.err.println("Connection: rethrowing " + ie);
}
throw ie; // rethrow exception
}
}
}
if (debug) {
System.err.println("Connection: end-of-stream detected: "
+ in);
}
} catch (IOException ex) {
if (debug) {
System.err.println("Connection: Caught " + ex);
}
closureReason = ex;
} finally {
cleanup(null, true); // cleanup
}
if (debug) {
System.err.println("Connection: Thread Exiting");
}
}
// This code must be uncommented to run the LdapAbandonTest.
/*public void sendSearchReqs(String dn, int numReqs) {
int i;
String attrs[] = null;
for(i = 1; i <= numReqs; i++) {
BerEncoder ber = new BerEncoder(2048);
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(i);
ber.beginSeq(LdapClient.LDAP_REQ_SEARCH);
ber.encodeString(dn == null ? "" : dn);
ber.encodeInt(0, LdapClient.LBER_ENUMERATED);
ber.encodeInt(3, LdapClient.LBER_ENUMERATED);
ber.encodeInt(0);
ber.encodeInt(0);
ber.encodeBoolean(true);
LdapClient.encodeFilter(ber, "");
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeStringArray(attrs);
ber.endSeq();
ber.endSeq();
ber.endSeq();
writeRequest(ber, i);
//System.err.println("wrote request " + i);
} catch (Exception ex) {
//System.err.println("ldap.search: Caught " + ex + " building req");
}
}
} */
}
|
apache/hive | 38,337 | ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionOptimizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.optimizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.conf.Constants;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.MemoryInfo;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.OperatorFactory;
import org.apache.hadoop.hive.ql.exec.OperatorUtils;
import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.SelectOperator;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.exec.Utilities.ReduceField;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.RecordIdentifier;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.SemanticDispatcher;
import org.apache.hadoop.hive.ql.lib.SemanticGraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.SemanticNodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.lib.SemanticRule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.type.ExprNodeTypeCheck;
import org.apache.hadoop.hive.ql.plan.ColStatistics;
import org.apache.hadoop.hive.ql.plan.DynamicPartitionCtx;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDescUtils;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.FileSinkDesc;
import org.apache.hadoop.hive.ql.plan.ListBucketingCtx;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
import org.apache.hadoop.hive.ql.plan.ReduceSinkDesc;
import org.apache.hadoop.hive.ql.plan.SelectDesc;
import org.apache.hadoop.hive.ql.plan.Statistics;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.util.NullOrdering;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.orc.OrcConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* When dynamic partitioning (with or without bucketing and sorting) is enabled, this optimization
* sorts the records on partition, bucket and sort columns respectively before inserting records
* into the destination table. This enables reducers to keep only one record writer all the time
* thereby reducing the the memory pressure on the reducers.
* Sorting is based on the Dynamic Partitioning context that is already created in the file sink operator.
* If that contains instructions for custom expression sorting, then this optimizer will disregard any partitioning or
* bucketing information of the Hive (table format) table, and will arrange the plan solely as per the custom exprs.
*/
public class SortedDynPartitionOptimizer extends Transform {
private static final Function<List<ExprNodeDesc>, ExprNodeDesc> BUCKET_SORT_EXPRESSION = cols -> {
try {
return ExprNodeGenericFuncDesc.newInstance(
FunctionRegistry.getFunctionInfo("bucket_number").getGenericUDF(), new ArrayList<>());
} catch (SemanticException e) {
throw new RuntimeException(e);
}
};
@Override
public ParseContext transform(ParseContext pCtx) throws SemanticException {
// create a walker which walks the tree in a DFS manner while maintaining the
// operator stack. The dispatcher generates the plan from the operator tree
Map<SemanticRule, SemanticNodeProcessor> opRules = new LinkedHashMap<SemanticRule, SemanticNodeProcessor>();
String FS = FileSinkOperator.getOperatorName() + "%";
opRules.put(new RuleRegExp("Sorted Dynamic Partition", FS), getSortDynPartProc(pCtx));
SemanticDispatcher disp = new DefaultRuleDispatcher(null, opRules, null);
SemanticGraphWalker ogw = new DefaultGraphWalker(disp);
ArrayList<Node> topNodes = new ArrayList<Node>();
topNodes.addAll(pCtx.getTopOps().values());
ogw.startWalking(topNodes, null);
return pCtx;
}
private SemanticNodeProcessor getSortDynPartProc(ParseContext pCtx) {
return new SortedDynamicPartitionProc(pCtx);
}
class SortedDynamicPartitionProc implements SemanticNodeProcessor {
private final Logger LOG = LoggerFactory.getLogger(SortedDynPartitionOptimizer.class);
protected ParseContext parseCtx;
public SortedDynamicPartitionProc(ParseContext pCtx) {
this.parseCtx = pCtx;
}
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
// introduce RS and EX before FS. If the operator tree already contains
// RS then ReduceSinkDeDuplication optimization should merge them
FileSinkOperator fsOp = (FileSinkOperator) nd;
LOG.info("Sorted dynamic partitioning optimization kicked in..");
// if not dynamic partitioning then bail out
if (fsOp.getConf().getDynPartCtx() == null) {
LOG.debug("Bailing out of sort dynamic partition optimization as dynamic partitioning context is null");
return null;
}
// if list bucketing then bail out
ListBucketingCtx lbCtx = fsOp.getConf().getLbCtx();
if (lbCtx != null && !lbCtx.getSkewedColNames().isEmpty()
&& !lbCtx.getSkewedColValues().isEmpty()) {
LOG.debug("Bailing out of sort dynamic partition optimization as list bucketing is enabled");
return null;
}
Table destTable = fsOp.getConf().getTable();
if (destTable == null) {
LOG.debug("Bailing out of sort dynamic partition optimization as destination table is null");
return null;
}
if (destTable.isMaterializedView() &&
(destTable.getProperty(Constants.MATERIALIZED_VIEW_SORT_COLUMNS) != null ||
destTable.getProperty(Constants.MATERIALIZED_VIEW_DISTRIBUTE_COLUMNS) != null)) {
LOG.debug("Bailing out of sort dynamic partition optimization as destination is a materialized view"
+ "with CLUSTER/SORT/DISTRIBUTE spec");
return null;
}
// unlink connection between FS and its parent
Operator<? extends OperatorDesc> fsParent = fsOp.getParentOperators().get(0);
DynamicPartitionCtx dpCtx = fsOp.getConf().getDynPartCtx();
ArrayList<ColumnInfo> parentCols = Lists.newArrayList(fsParent.getSchema().getSignature());
ArrayList<ExprNodeDesc> allRSCols = Lists.newArrayList();
for (ColumnInfo ci : parentCols) {
allRSCols.add(new ExprNodeColumnDesc(ci));
}
// if all dp columns / custom sort expressions got constant folded then disable this optimization
if (allStaticPartitions(fsParent, allRSCols, dpCtx)) {
LOG.debug("Bailing out of sorted dynamic partition optimizer as all dynamic partition" +
" columns got constant folded (static partitioning)");
return null;
}
List<Integer> partitionPositions = getPartitionPositions(dpCtx, fsParent.getSchema());
LinkedList<Function<List<ExprNodeDesc>, ExprNodeDesc>> customSortExprs =
new LinkedList<>(dpCtx.getCustomSortExpressions());
LinkedList<Integer> customSortOrder = new LinkedList<>(dpCtx.getCustomSortOrder());
LinkedList<Integer> customNullOrder = new LinkedList<>(dpCtx.getCustomSortNullOrder());
// If custom sort expressions are present, there is an explicit requirement to do sorting
if (customSortExprs.isEmpty() && !shouldDo(partitionPositions, fsParent)) {
return null;
}
// if RS is inserted by enforce bucketing or sorting, we need to remove it
// since ReduceSinkDeDuplication will not merge them to single RS.
// RS inserted by enforce bucketing/sorting will have bucketing column in
// reduce sink key whereas RS inserted by this optimization will have
// partition columns followed by bucket number followed by sort columns in
// the reduce sink key. Since both key columns are not prefix subset
// ReduceSinkDeDuplication will not merge them together resulting in 2 MR jobs.
// To avoid that we will remove the RS (and EX) inserted by enforce bucketing/sorting.
if (!removeRSInsertedByEnforceBucketing(fsOp)) {
LOG.debug("Bailing out of sort dynamic partition optimization as some partition columns " +
"got constant folded.");
return null;
}
// unlink connection between FS and its parent
fsParent = fsOp.getParentOperators().get(0);
// store the index of the file sink operator to later insert the modified operator with RS at the same position
int fsOpIndex = fsParent.getChildOperators().indexOf(fsOp);
fsParent.getChildOperators().remove(fsOp);
// if enforce bucketing/sorting is disabled numBuckets will not be set.
// set the number of buckets here to ensure creation of empty buckets
int numBuckets = destTable.getNumBuckets();
dpCtx.setNumBuckets(numBuckets);
// Get the positions for partition, bucket and sort columns
List<Integer> bucketPositions = getBucketPositions(destTable.getBucketCols(),
destTable.getCols());
List<Integer> sortPositions = null;
List<Integer> sortOrder = null;
ArrayList<ExprNodeDesc> bucketColumns = null;
if (fsOp.getConf().getWriteType() == AcidUtils.Operation.UPDATE ||
fsOp.getConf().getWriteType() == AcidUtils.Operation.DELETE) {
// When doing updates and deletes we always want to sort on the rowid because the ACID
// reader will expect this sort order when doing reads. So
// ignore whatever comes from the table and enforce this sort order instead.
sortPositions = Collections.singletonList(0);
sortOrder = Collections.singletonList(1); // 1 means asc, could really use enum here in the thrift if
/**
* ROW__ID is always the 1st column of Insert representing Update/Delete operation
* (set up in {@link org.apache.hadoop.hive.ql.parse.UpdateDeleteSemanticAnalyzer})
* and we wrap it in UDFToInteger
* (in {@link org.apache.hadoop.hive.ql.parse.SemanticAnalyzer#getPartitionColsFromBucketColsForUpdateDelete(Operator, boolean)})
* which extracts bucketId from it
* see {@link org.apache.hadoop.hive.ql.udf.UDFToInteger#evaluate(RecordIdentifier)}*/
ColumnInfo ci = fsParent.getSchema().getSignature().get(0);
if (!VirtualColumn.ROWID.getTypeInfo().equals(ci.getType())) {
throw new IllegalStateException("expected 1st column to be ROW__ID but got wrong type: " + ci.toString());
}
if (numBuckets > 0) {
bucketColumns = new ArrayList<>();
//add a cast(ROW__ID as int) to wrap in UDFToInteger()
bucketColumns.add(ExprNodeTypeCheck.getExprNodeDefaultExprProcessor()
.createConversionCast(new ExprNodeColumnDesc(ci), TypeInfoFactory.intTypeInfo));
}
} else {
if (!destTable.getSortCols().isEmpty()) {
// Sort columns specified by table
sortPositions = getSortPositions(destTable.getSortCols(), destTable.getCols());
sortOrder = getSortOrders(destTable.getSortCols(), destTable.getCols());
} else if (HiveConf.getBoolVar(this.parseCtx.getConf(), HiveConf.ConfVars.HIVE_SORT_WHEN_BUCKETING) &&
!bucketPositions.isEmpty()) {
// We use clustered columns as sort columns
sortPositions = new ArrayList<>(bucketPositions);
sortOrder = sortPositions.stream().map(e -> 1).collect(Collectors.toList());
} else {
// Infer sort columns from operator tree
sortPositions = Lists.newArrayList();
sortOrder = Lists.newArrayList();
inferSortPositions(fsParent, sortPositions, sortOrder);
}
List<ColumnInfo> colInfos = fsParent.getSchema().getSignature();
bucketColumns = getPositionsToExprNodes(bucketPositions, colInfos);
}
List<Integer> sortNullOrder = new ArrayList<>();
for (int order : sortOrder) {
sortNullOrder.add(NullOrdering.defaultNullOrder(order, parseCtx.getConf()).getCode());
}
LOG.debug("Got sort order");
for (int i : sortPositions) {
LOG.debug("sort position " + i);
}
for (int i : sortOrder) {
LOG.debug("sort order " + i);
}
for (int i : sortNullOrder) {
LOG.debug("sort null order " + i);
}
// update file sink descriptor
fsOp.getConf().setMultiFileSpray(false);
fsOp.getConf().setNumFiles(1);
fsOp.getConf().setTotalFiles(1);
// Create ReduceSink operator
ReduceSinkOperator rsOp = getReduceSinkOp(partitionPositions, sortPositions, sortOrder,
sortNullOrder, customSortExprs, customSortOrder, customNullOrder, allRSCols, bucketColumns, numBuckets,
fsParent, fsOp.getConf().getWriteType());
// we have to make sure not to reorder the child operators as it might cause weird behavior in the tasks at
// the same level. when there is auto stats gather at the same level as another operation then it might
// cause unnecessary preemption. Maintaining the order here to avoid such preemption and possible errors
// Ref TEZ-3296
fsParent.getChildOperators().remove(rsOp);
fsParent.getChildOperators().add(fsOpIndex, rsOp);
rsOp.getConf().setBucketingVersion(fsOp.getConf().getBucketingVersion());
List<ExprNodeDesc> descs = new ArrayList<ExprNodeDesc>(allRSCols.size());
List<String> colNames = new ArrayList<String>();
String colName;
final List<ColumnInfo> fileSinkSchema = fsOp.getSchema().getSignature();
for (int i = 0; i < allRSCols.size(); i++) {
ExprNodeDesc col = allRSCols.get(i);
ExprNodeDesc newColumnExpr = null;
colName = col.getExprString();
colNames.add(colName);
if (partitionPositions.contains(i) || sortPositions.contains(i)) {
newColumnExpr = (new ExprNodeColumnDesc(col.getTypeInfo(), ReduceField.KEY.toString()+"."+colName, null, false));
} else {
newColumnExpr = (new ExprNodeColumnDesc(col.getTypeInfo(), ReduceField.VALUE.toString()+"."+colName, null, false));
}
// make sure column type matches with expected types in FS op
if(i < fileSinkSchema.size()) {
final ColumnInfo fsColInfo = fileSinkSchema.get(i);
if (!newColumnExpr.getTypeInfo().equals(fsColInfo.getType())) {
newColumnExpr = ExprNodeTypeCheck.getExprNodeDefaultExprProcessor()
.createConversionCast(newColumnExpr, (PrimitiveTypeInfo) fsColInfo.getType());
}
}
descs.add(newColumnExpr);
}
RowSchema selRS = new RowSchema(fsParent.getSchema());
if (bucketColumns != null && !bucketColumns.isEmpty()) {
customSortExprs.add(BUCKET_SORT_EXPRESSION);
}
for (Function<List<ExprNodeDesc>, ExprNodeDesc> customSortExpr : customSortExprs) {
ExprNodeDesc colExpr = customSortExpr.apply(allRSCols);
String customSortColName = colExpr.getExprString();
TypeInfo customSortColTypeInfo = colExpr.getTypeInfo();
descs.add(new ExprNodeColumnDesc(customSortColTypeInfo, ReduceField.KEY + "." + customSortColName,
null, false));
colNames.add(customSortColName);
ColumnInfo ci = new ColumnInfo(
customSortColName, customSortColTypeInfo, selRS.getSignature().get(0).getTabAlias(), true, true);
selRS.getSignature().add(ci);
rsOp.getSchema().getSignature().add(ci);
}
// Create SelectDesc
SelectDesc selConf = new SelectDesc(descs, colNames);
// Create Select Operator
SelectOperator selOp = (SelectOperator) OperatorFactory.getAndMakeChild(
selConf, selRS, rsOp);
// link SEL to FS
fsOp.getParentOperators().clear();
fsOp.getParentOperators().add(selOp);
selOp.getChildOperators().add(fsOp);
// Set if partition sorted or partition bucket sorted
fsOp.getConf().setDpSortState(FileSinkDesc.DPSortState.PARTITION_SORTED);
if (bucketColumns!=null && !bucketColumns.isEmpty()) {
fsOp.getConf().setDpSortState(FileSinkDesc.DPSortState.PARTITION_BUCKET_SORTED);
}
// update partition column info in FS descriptor
fsOp.getConf().setPartitionCols(rsOp.getConf().getPartitionCols());
rsOp.setStatistics(rsOp.getParentOperators().get(0).getStatistics());
LOG.info("Inserted " + rsOp.getOperatorId() + " and " + selOp.getOperatorId()
+ " as parent of " + fsOp.getOperatorId() + " and child of " + fsParent.getOperatorId());
parseCtx.setReduceSinkAddedBySortedDynPartition(true);
return null;
}
private boolean allStaticPartitions(Operator<? extends OperatorDesc> op, List<ExprNodeDesc> allRSCols,
final DynamicPartitionCtx dynPartCtx) {
if (op.getColumnExprMap() == null) {
// find first operator upstream with valid (non-null) column expression map
for (Operator<? extends OperatorDesc> parent : op.getParentOperators()) {
if (parent.getColumnExprMap() != null) {
op = parent;
break;
}
}
}
// No mappings for any columns
if (op.getColumnExprMap() == null) {
return false;
}
List<String> referencedSortColumnNames = new LinkedList<>();
List<Function<List<ExprNodeDesc>, ExprNodeDesc>> customSortExprs = dynPartCtx.getCustomSortExpressions();
if (customSortExprs != null && !customSortExprs.isEmpty()) {
Set<ExprNodeColumnDesc> columnDescs = new HashSet<>();
// Find relevant column descs (e.g. _col0, _col2) for each sort expression
for (Function<List<ExprNodeDesc>, ExprNodeDesc> customSortExpr : customSortExprs) {
ExprNodeDesc sortExpressionForRSSchema = customSortExpr.apply(allRSCols);
columnDescs.addAll(ExprNodeDescUtils.findAllColumnDescs(sortExpressionForRSSchema));
}
for (ExprNodeColumnDesc columnDesc : columnDescs) {
referencedSortColumnNames.add(columnDesc.getColumn());
}
} else {
int numDpCols = dynPartCtx.getNumDPCols();
int numCols = op.getSchema().getColumnNames().size();
referencedSortColumnNames.addAll(op.getSchema().getColumnNames().subList(numCols - numDpCols, numCols));
}
for(String dpCol : referencedSortColumnNames) {
ExprNodeDesc end = ExprNodeDescUtils.findConstantExprOrigin(dpCol, op);
if (!(end instanceof ExprNodeConstantDesc)) {
// There is at least 1 column with no constant mapping -> we will need to do the sorting
return false;
}
}
// All columns had constant mappings
return true;
}
// Remove RS and SEL introduced by enforce bucketing/sorting config
// Convert PARENT -> RS -> SEL -> FS to PARENT -> FS
private boolean removeRSInsertedByEnforceBucketing(FileSinkOperator fsOp) {
Set<ReduceSinkOperator> reduceSinks = OperatorUtils.findOperatorsUpstream(fsOp,
ReduceSinkOperator.class);
Operator<? extends OperatorDesc> rsToRemove = null;
List<ReduceSinkOperator> rsOps = parseCtx
.getReduceSinkOperatorsAddedByEnforceBucketingSorting();
boolean found = false;
// iterate through all RS and locate the one introduce by enforce bucketing
for (ReduceSinkOperator reduceSink : reduceSinks) {
for (ReduceSinkOperator rsOp : rsOps) {
if (reduceSink.equals(rsOp)) {
rsToRemove = reduceSink;
found = true;
break;
}
}
if (found) {
break;
}
}
// iF RS is found remove it and its child (EX) and connect its parent
// and grand child
if (found) {
Operator<? extends OperatorDesc> rsParent = rsToRemove.getParentOperators().get(0);
// RS is expected to have exactly ONE child
assert(rsToRemove.getChildOperators().size() == 1);
Operator<? extends OperatorDesc> rsChildToRemove = rsToRemove.getChildOperators().get(0);
if (!(rsChildToRemove instanceof SelectOperator) || rsParent.getSchema().getSignature().size()
!= rsChildToRemove.getSchema().getSignature().size()) {
// if schema size cannot be matched, then it could be because of constant folding
// converting partition column expression to constant expression. The constant
// expression will then get pruned by column pruner since it will not reference to
// any columns.
return false;
}
// if child is select and contains expression which isn't column it shouldn't
// be removed because otherwise we will end up with different types/schema later
// while introducing select for RS
for(ExprNodeDesc expr: rsChildToRemove.getColumnExprMap().values()){
if(!(expr instanceof ExprNodeColumnDesc)){
return false;
}
}
List<Operator<? extends OperatorDesc>> rsGrandChildren = rsChildToRemove.getChildOperators();
rsParent.getChildOperators().remove(rsToRemove);
rsParent.getChildOperators().addAll(rsGrandChildren);
// fix grandchildren
for (Operator<? extends OperatorDesc> rsGrandChild: rsGrandChildren) {
rsGrandChild.getParentOperators().clear();
rsGrandChild.getParentOperators().add(rsParent);
}
LOG.info("Removed " + rsToRemove.getOperatorId() + " and " + rsChildToRemove.getOperatorId()
+ " as it was introduced by enforce bucketing/sorting.");
}
return true;
}
private List<Integer> getPartitionPositions(DynamicPartitionCtx dpCtx, RowSchema schema) {
int numPartCols = dpCtx.getNumDPCols();
int numCols = schema.getSignature().size();
List<Integer> partPos = Lists.newArrayList();
// partition columns will always at the last
for (int i = numCols - numPartCols; i < numCols; i++) {
partPos.add(i);
}
return partPos;
}
// Get the bucket positions for the table
private List<Integer> getBucketPositions(List<String> tabBucketCols, List<FieldSchema> tabCols) {
List<Integer> posns = new ArrayList<Integer>();
for (String bucketCol : tabBucketCols) {
int pos = 0;
for (FieldSchema tabCol : tabCols) {
if (bucketCol.equals(tabCol.getName())) {
posns.add(pos);
break;
}
pos++;
}
}
return posns;
}
// Try to infer possible sort columns in the query
// i.e. the sequence must be pRS-SEL*-fsParent
// Returns true if columns could be inferred, false otherwise
private void inferSortPositions(Operator<? extends OperatorDesc> fsParent,
List<Integer> sortPositions, List<Integer> sortOrder) throws SemanticException {
// If it is not a SEL operator, we bail out
if (!(fsParent instanceof SelectOperator)) {
return;
}
SelectOperator pSel = (SelectOperator) fsParent;
Operator<? extends OperatorDesc> parent = pSel;
while (!(parent instanceof ReduceSinkOperator)) {
if (parent.getNumParent() != 1 ||
!(parent instanceof SelectOperator)) {
return;
}
parent = parent.getParentOperators().get(0);
}
// Backtrack SEL columns to pRS
List<ExprNodeDesc> selColsInPRS =
ExprNodeDescUtils.backtrack(pSel.getConf().getColList(), pSel, parent);
ReduceSinkOperator pRS = (ReduceSinkOperator) parent;
for (int i = 0; i < pRS.getConf().getKeyCols().size(); i++) {
ExprNodeDesc col = pRS.getConf().getKeyCols().get(i);
int pos = selColsInPRS.indexOf(col);
if (pos == -1) {
sortPositions.clear();
sortOrder.clear();
return;
}
sortPositions.add(pos);
sortOrder.add(pRS.getConf().getOrder().charAt(i) == '+' ? 1 : 0); // 1 asc, 0 desc
}
}
public ReduceSinkOperator getReduceSinkOp(List<Integer> partitionPositions, List<Integer> sortPositions,
List<Integer> sortOrder, List<Integer> sortNullOrder,
List<Function<List<ExprNodeDesc>, ExprNodeDesc>> customSortExprs,
List<Integer> customSortOrder, List<Integer> customSortNullOrder,
ArrayList<ExprNodeDesc> allCols, ArrayList<ExprNodeDesc> bucketColumns,
int numBuckets, Operator<? extends OperatorDesc> parent, AcidUtils.Operation writeType) {
// Order of KEY columns, if custom sort is present partition and bucket columns are disregarded:
// 0) Custom sort expressions
// 1) Partition columns
// 2) Bucket number column
// 3) Sort columns
boolean customSortExprPresent = customSortExprs != null && !customSortExprs.isEmpty();
Set<Integer> keyColsPosInVal = Sets.newLinkedHashSet();
ArrayList<ExprNodeDesc> keyCols = Lists.newArrayList();
List<Integer> newSortOrder = Lists.newArrayList();
List<Integer> newSortNullOrder = Lists.newArrayList();
if (customSortExprPresent) {
partitionPositions = new ArrayList<>();
bucketColumns = new ArrayList<>();
numBuckets = -1;
}
keyColsPosInVal.addAll(partitionPositions);
if (bucketColumns != null && !bucketColumns.isEmpty()) {
keyColsPosInVal.add(-1);
}
keyColsPosInVal.addAll(sortPositions);
Integer order = 1;
// by default partition and bucket columns are sorted in ascending order
if (sortOrder != null && !sortOrder.isEmpty()) {
if (sortOrder.get(0) == 0) {
order = 0;
}
}
for (Integer ignored : keyColsPosInVal) {
newSortOrder.add(order);
}
if (customSortExprPresent) {
for (int i = 0; i < customSortExprs.size() - customSortOrder.size(); i++) {
newSortOrder.add(order);
}
newSortOrder.addAll(customSortOrder);
}
String orderStr = "";
for (Integer i : newSortOrder) {
if (i == 1) {
orderStr += "+";
} else {
orderStr += "-";
}
}
char nullOrder = NullOrdering.defaultNullOrder(order, parseCtx.getConf()).getSign();
if (sortNullOrder != null && !sortNullOrder.isEmpty()) {
nullOrder = NullOrdering.fromCode(sortNullOrder.get(0)).getSign();
}
StringBuilder nullOrderStr = new StringBuilder(StringUtils.repeat(nullOrder, keyColsPosInVal.size()));
if (customSortExprPresent) {
for (int i = 0; i < customSortExprs.size() - customSortNullOrder.size(); i++) {
nullOrderStr.append(nullOrder);
}
for (int i = 0; i < customSortNullOrder.size(); ++i) {
nullOrderStr.append(NullOrdering.fromCode(customSortNullOrder.get(i)).getSign());
}
}
Map<String, ExprNodeDesc> colExprMap = Maps.newHashMap();
ArrayList<ExprNodeDesc> partCols = Lists.newArrayList();
for (Function<List<ExprNodeDesc>, ExprNodeDesc> customSortExpr : customSortExprs) {
ExprNodeDesc colExpr = customSortExpr.apply(allCols);
// Custom sort expressions are marked as KEYs, which is required for sorting the rows that are going for
// a particular reducer instance. They also need to be marked as 'partition' columns for MapReduce shuffle
// phase, in order to gather the same keys to the same reducer instances.
keyCols.add(colExpr);
partCols.add(colExpr);
}
// we will clone here as RS will update bucket column key with its
// corresponding with bucket number and hence their OIs
for (Integer idx : keyColsPosInVal) {
if (idx == -1) {
keyCols.add(BUCKET_SORT_EXPRESSION.apply(allCols));
} else {
keyCols.add(allCols.get(idx).clone());
}
}
ArrayList<ExprNodeDesc> valCols = Lists.newArrayList();
for (int i = 0; i < allCols.size(); i++) {
if (!keyColsPosInVal.contains(i)) {
valCols.add(allCols.get(i).clone());
}
}
for (Integer idx : partitionPositions) {
partCols.add(allCols.get(idx).clone());
}
// in the absence of SORTED BY clause, the sorted dynamic partition insert
// should honor the ordering of records provided by ORDER BY in SELECT statement
ReduceSinkOperator parentRSOp = OperatorUtils.findSingleOperatorUpstream(parent,
ReduceSinkOperator.class);
if (parentRSOp != null && parseCtx.getQueryProperties().hasOuterOrderBy()) {
String parentRSOpOrder = parentRSOp.getConf().getOrder();
String parentRSOpNullOrder = parentRSOp.getConf().getNullOrder();
if (parentRSOpOrder != null && !parentRSOpOrder.isEmpty() && sortPositions.isEmpty()) {
keyCols.addAll(parentRSOp.getConf().getKeyCols());
orderStr += parentRSOpOrder;
nullOrderStr.append(parentRSOpNullOrder);
}
}
// map _col0 to KEY._col0, etc
Map<String, String> nameMapping = new HashMap<>();
ArrayList<String> keyColNames = Lists.newArrayList();
Set<String> computedFields = new HashSet<>();
for (ExprNodeDesc keyCol : keyCols) {
String keyColName = keyCol.getExprString();
keyColNames.add(keyColName);
colExprMap.put(Utilities.ReduceField.KEY + "." +keyColName, keyCol);
nameMapping.put(keyColName, Utilities.ReduceField.KEY + "." + keyColName);
}
ArrayList<String> valColNames = Lists.newArrayList();
for (ExprNodeDesc valCol : valCols) {
String colName = valCol.getExprString();
valColNames.add(colName);
colExprMap.put(Utilities.ReduceField.VALUE + "." + colName, valCol);
if (nameMapping.containsKey(colName)) {
computedFields.add(nameMapping.get(colName));
}
nameMapping.put(colName, Utilities.ReduceField.VALUE + "." + colName);
}
// Create Key/Value TableDesc. When the operator plan is split into MR tasks,
// the reduce operator will initialize Extract operator with information
// from Key and Value TableDesc
List<FieldSchema> fields = PlanUtils.getFieldSchemasFromColumnList(keyCols,
keyColNames, 0, "");
TableDesc keyTable = PlanUtils.getReduceKeyTableDesc(fields, orderStr, nullOrderStr.toString());
List<FieldSchema> valFields = PlanUtils.getFieldSchemasFromColumnList(valCols,
valColNames, 0, "");
TableDesc valueTable = PlanUtils.getReduceValueTableDesc(valFields);
List<List<Integer>> distinctColumnIndices = Lists.newArrayList();
// Number of reducers is set to default (-1)
ReduceSinkDesc rsConf = new ReduceSinkDesc(keyCols, keyCols.size(), valCols,
keyColNames, distinctColumnIndices, valColNames, -1, partCols, -1, keyTable,
valueTable, writeType);
rsConf.setBucketCols(bucketColumns);
rsConf.setNumBuckets(numBuckets);
rsConf.getComputedFields().addAll(computedFields);
ArrayList<ColumnInfo> signature = new ArrayList<>();
for (int index = 0; index < parent.getSchema().getSignature().size(); index++) {
ColumnInfo colInfo = new ColumnInfo(parent.getSchema().getSignature().get(index));
colInfo.setInternalName(nameMapping.get(colInfo.getInternalName()));
signature.add(colInfo);
}
ReduceSinkOperator op = (ReduceSinkOperator) OperatorFactory.getAndMakeChild(
rsConf, new RowSchema(signature), parent);
rsConf.addComputedField(Utilities.ReduceField.KEY + "." + BUCKET_SORT_EXPRESSION.apply(allCols).getExprString());
for (Function<List<ExprNodeDesc>, ExprNodeDesc> customSortExpr : customSortExprs) {
rsConf.addComputedField(Utilities.ReduceField.KEY + "." + customSortExpr.apply(allCols).getExprString());
}
op.setColumnExprMap(colExprMap);
return op;
}
/**
* Get the sort positions for the sort columns.
*
* @param tabSortCols
* @param tabCols
* @return
*/
private List<Integer> getSortPositions(List<Order> tabSortCols,
List<FieldSchema> tabCols) {
List<Integer> sortPositions = Lists.newArrayList();
for (Order sortCol : tabSortCols) {
int pos = 0;
for (FieldSchema tabCol : tabCols) {
if (sortCol.getCol().equals(tabCol.getName())) {
sortPositions.add(pos);
break;
}
pos++;
}
}
return sortPositions;
}
/**
* Get the sort order for the sort columns.
*
* @param tabSortCols
* @param tabCols
* @return
*/
private List<Integer> getSortOrders(List<Order> tabSortCols,
List<FieldSchema> tabCols) {
List<Integer> sortOrders = Lists.newArrayList();
for (Order sortCol : tabSortCols) {
for (FieldSchema tabCol : tabCols) {
if (sortCol.getCol().equals(tabCol.getName())) {
sortOrders.add(sortCol.getOrder());
break;
}
}
}
return sortOrders;
}
private ArrayList<ExprNodeDesc> getPositionsToExprNodes(List<Integer> pos,
List<ColumnInfo> colInfos) {
ArrayList<ExprNodeDesc> cols = Lists.newArrayList();
for (Integer idx : pos) {
ColumnInfo ci = colInfos.get(idx);
ExprNodeColumnDesc encd = new ExprNodeColumnDesc(ci);
cols.add(encd);
}
return cols;
}
// the idea is to estimate how many number of writers this insert can spun up.
// Writers are proportional to number of partitions being inserted i.e cardinality of the partition columns
// if these writers are more than number of writers allowed within the memory pool (estimated) we go ahead with
// adding extra RS
// The way max number of writers allowed are computed based on
// (executor/container memory) * (percentage of memory taken by orc)
// and dividing that by max memory (stripe size) taken by a single writer.
private boolean shouldDo(List<Integer> partitionPos, Operator<? extends OperatorDesc> fsParent) {
int threshold = HiveConf.getIntVar(this.parseCtx.getConf(),
HiveConf.ConfVars.HIVE_OPT_SORT_DYNAMIC_PARTITION_THRESHOLD);
long MAX_WRITERS = -1;
switch (threshold) {
case -1:
return false;
case 0:
break;
case 1:
return true;
default:
MAX_WRITERS = threshold;
break;
}
Statistics tStats = fsParent.getStatistics();
if (tStats == null) {
return true;
}
List<ColStatistics> colStats = tStats.getColumnStats();
if (colStats == null || colStats.isEmpty()) {
return true;
}
long partCardinality = 1;
// compute cardinality for partition columns
for (Integer idx : partitionPos) {
ColumnInfo ci = fsParent.getSchema().getSignature().get(idx);
ColStatistics partStats = fsParent.getStatistics().getColumnStatisticsFromColName(ci.getInternalName());
if (partStats == null) {
// statistics for this partition are for some reason not available
return true;
}
partCardinality = partCardinality * partStats.getCountDistint();
}
if (MAX_WRITERS < 0) {
double orcMemPool = this.parseCtx.getConf().getDouble(OrcConf.MEMORY_POOL.getHiveConfName(),
(Double) OrcConf.MEMORY_POOL.getDefaultValue());
long orcStripSize = this.parseCtx.getConf().getLong(OrcConf.STRIPE_SIZE.getHiveConfName(),
(Long) OrcConf.STRIPE_SIZE.getDefaultValue());
MemoryInfo memoryInfo = new MemoryInfo(this.parseCtx.getConf());
LOG.debug("Memory info during SDPO opt: {}", memoryInfo);
long executorMem = memoryInfo.getMaxExecutorMemory();
MAX_WRITERS = (long) (executorMem * orcMemPool) / orcStripSize;
}
if (partCardinality <= MAX_WRITERS) {
return false;
}
return true;
}
}
}
|
apache/druid | 38,357 | server/src/main/java/org/apache/druid/client/CachingClusteredClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.client;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.RangeSet;
import com.google.common.collect.Sets;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Bytes;
import com.google.inject.Inject;
import org.apache.druid.client.cache.Cache;
import org.apache.druid.client.cache.CacheConfig;
import org.apache.druid.client.cache.CachePopulator;
import org.apache.druid.client.selector.ServerSelector;
import org.apache.druid.guice.annotations.Client;
import org.apache.druid.guice.annotations.Merging;
import org.apache.druid.guice.annotations.Smile;
import org.apache.druid.guice.http.DruidHttpClientConfig;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.guava.BaseSequence;
import org.apache.druid.java.util.common.guava.LazySequence;
import org.apache.druid.java.util.common.guava.ParallelMergeCombiningSequence;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.query.BrokerParallelMergeConfig;
import org.apache.druid.query.BySegmentResultValueClass;
import org.apache.druid.query.CacheStrategy;
import org.apache.druid.query.CloneQueryMode;
import org.apache.druid.query.Queries;
import org.apache.druid.query.Query;
import org.apache.druid.query.QueryContext;
import org.apache.druid.query.QueryContexts;
import org.apache.druid.query.QueryMetrics;
import org.apache.druid.query.QueryPlus;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryRunnerFactoryConglomerate;
import org.apache.druid.query.QuerySegmentWalker;
import org.apache.druid.query.QueryToolChest;
import org.apache.druid.query.Result;
import org.apache.druid.query.SegmentDescriptor;
import org.apache.druid.query.aggregation.MetricManipulatorFns;
import org.apache.druid.query.context.ResponseContext;
import org.apache.druid.query.filter.DimFilterUtils;
import org.apache.druid.query.planning.ExecutionVertex;
import org.apache.druid.server.QueryResource;
import org.apache.druid.server.QueryScheduler;
import org.apache.druid.server.coordination.DruidServerMetadata;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.Overshadowable;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.TimelineLookup;
import org.apache.druid.timeline.TimelineObjectHolder;
import org.apache.druid.timeline.VersionedIntervalTimeline;
import org.apache.druid.timeline.VersionedIntervalTimeline.PartitionChunkEntry;
import org.apache.druid.timeline.partition.PartitionChunk;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ForkJoinPool;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* This is the class on the Broker that is responsible for making native Druid queries to a cluster of data servers.
*
* The main user of this class is {@link org.apache.druid.server.ClientQuerySegmentWalker}. In tests, its behavior
* is partially mimicked by TestClusterQuerySegmentWalker.
*/
public class CachingClusteredClient implements QuerySegmentWalker
{
private static final EmittingLogger log = new EmittingLogger(CachingClusteredClient.class);
private final QueryRunnerFactoryConglomerate conglomerate;
private final TimelineServerView serverView;
private final Cache cache;
private final ObjectMapper objectMapper;
private final CachePopulator cachePopulator;
private final CacheConfig cacheConfig;
private final DruidHttpClientConfig httpClientConfig;
private final BrokerParallelMergeConfig parallelMergeConfig;
private final ForkJoinPool pool;
private final QueryScheduler scheduler;
private final ServiceEmitter emitter;
@Inject
public CachingClusteredClient(
QueryRunnerFactoryConglomerate conglomerate,
TimelineServerView serverView,
Cache cache,
@Smile ObjectMapper objectMapper,
CachePopulator cachePopulator,
CacheConfig cacheConfig,
@Client DruidHttpClientConfig httpClientConfig,
BrokerParallelMergeConfig parallelMergeConfig,
@Merging ForkJoinPool pool,
QueryScheduler scheduler,
ServiceEmitter emitter
)
{
this.conglomerate = conglomerate;
this.serverView = serverView;
this.cache = cache;
this.objectMapper = objectMapper;
this.cachePopulator = cachePopulator;
this.cacheConfig = cacheConfig;
this.httpClientConfig = httpClientConfig;
this.parallelMergeConfig = parallelMergeConfig;
this.pool = pool;
this.scheduler = scheduler;
this.emitter = emitter;
if (cacheConfig.isQueryCacheable(Query.GROUP_BY) && (cacheConfig.isUseCache() || cacheConfig.isPopulateCache())) {
log.warn(
"Even though groupBy caching is enabled in your configuration, v2 groupBys will not be cached on the broker. "
+ "Consider enabling caching on your data nodes if it is not already enabled."
);
}
serverView.registerSegmentCallback(
Execs.singleThreaded("CCClient-ServerView-CB-%d"),
new ServerView.BaseSegmentCallback()
{
@Override
public ServerView.CallbackAction segmentRemoved(DruidServerMetadata server, DataSegment segment)
{
CachingClusteredClient.this.cache.close(segment.getId().toString());
return ServerView.CallbackAction.CONTINUE;
}
}
);
}
@Override
public <T> QueryRunner<T> getQueryRunnerForIntervals(final Query<T> query, final Iterable<Interval> intervals)
{
return new QueryRunner<>()
{
@Override
public Sequence<T> run(final QueryPlus<T> queryPlus, final ResponseContext responseContext)
{
return CachingClusteredClient.this.run(queryPlus, responseContext, timeline -> timeline, false);
}
};
}
/**
* Run a query. The timelineConverter will be given the "master" timeline and can be used to return a different
* timeline, if desired. This is used by getQueryRunnerForSegments.
*/
private <T> Sequence<T> run(
final QueryPlus<T> queryPlus,
final ResponseContext responseContext,
final UnaryOperator<TimelineLookup<String, ServerSelector>> timelineConverter,
final boolean specificSegments
)
{
final ClusterQueryResult<T> result = new SpecificQueryRunnable<>(queryPlus, responseContext)
.run(timelineConverter, specificSegments);
initializeNumRemainingResponsesInResponseContext(queryPlus.getQuery(), responseContext, result.numQueryServers);
return result.sequence;
}
private static <T> void initializeNumRemainingResponsesInResponseContext(
final Query<T> query,
final ResponseContext responseContext,
final int numQueryServers
)
{
responseContext.addRemainingResponse(query.getMostSpecificId(), numQueryServers);
}
@Override
public <T> QueryRunner<T> getQueryRunnerForSegments(final Query<T> query, final Iterable<SegmentDescriptor> specs)
{
return new QueryRunner<>()
{
@Override
public Sequence<T> run(final QueryPlus<T> queryPlus, final ResponseContext responseContext)
{
return CachingClusteredClient.this.run(
queryPlus,
responseContext,
new TimelineConverter(specs),
true
);
}
};
}
private static class ClusterQueryResult<T>
{
private final Sequence<T> sequence;
private final int numQueryServers;
private ClusterQueryResult(Sequence<T> sequence, int numQueryServers)
{
this.sequence = sequence;
this.numQueryServers = numQueryServers;
}
}
/**
* This class essentially encapsulates the major part of the logic of {@link CachingClusteredClient}. It's state and
* methods couldn't belong to {@link CachingClusteredClient} itself, because they depend on the specific query object
* being run, but {@link QuerySegmentWalker} API is designed so that implementations should be able to accept
* arbitrary queries.
*/
private class SpecificQueryRunnable<T>
{
private final ResponseContext responseContext;
private QueryPlus<T> queryPlus;
private Query<T> query;
private final QueryToolChest<T, Query<T>> toolChest;
@Nullable
private final CacheStrategy<T, Object, Query<T>> strategy;
private final boolean useCache;
private final boolean populateCache;
private final boolean isBySegment;
private final int uncoveredIntervalsLimit;
private final Map<String, Cache.NamedKey> cachePopulatorKeyMap = new HashMap<>();
private final ExecutionVertex ev;
private final List<Interval> intervals;
private final CacheKeyManager<T> cacheKeyManager;
SpecificQueryRunnable(final QueryPlus<T> queryPlus, final ResponseContext responseContext)
{
this.queryPlus = queryPlus;
this.responseContext = responseContext;
this.query = queryPlus.getQuery();
this.toolChest = conglomerate.getToolChest(query);
this.strategy = toolChest.getCacheStrategy(query, objectMapper);
this.ev = ExecutionVertex.of(query);
this.useCache = CacheUtil.isUseSegmentCache(query, strategy, cacheConfig, CacheUtil.ServerType.BROKER);
this.populateCache = CacheUtil.isPopulateSegmentCache(query, strategy, cacheConfig, CacheUtil.ServerType.BROKER);
final QueryContext queryContext = query.context();
this.isBySegment = queryContext.isBySegment();
// Note that enabling this leads to putting uncovered intervals information in the response headers
// and might blow up in some cases https://github.com/apache/druid/issues/2108
this.uncoveredIntervalsLimit = queryContext.getUncoveredIntervalsLimit();
// For nested queries, we need to look at the intervals of the inner most query.
this.intervals = ev
.getEffectiveQuerySegmentSpec()
.getIntervals();
this.cacheKeyManager = new CacheKeyManager<>(
query,
strategy,
useCache,
populateCache
);
}
private ImmutableMap<String, Object> makeDownstreamQueryContext()
{
final ImmutableMap.Builder<String, Object> contextBuilder = new ImmutableMap.Builder<>();
final QueryContext queryContext = query.context();
final int priority = queryContext.getPriority();
contextBuilder.put(QueryContexts.PRIORITY_KEY, priority);
final String lane = queryContext.getLane();
if (lane != null) {
contextBuilder.put(QueryContexts.LANE_KEY, lane);
}
if (populateCache) {
// prevent down-stream nodes from caching results as well if we are populating the cache
contextBuilder.put(CacheConfig.POPULATE_CACHE, false);
contextBuilder.put(QueryContexts.BY_SEGMENT_KEY, true);
}
return contextBuilder.build();
}
/**
* Builds a query distribution and merge plan.
*
* This method returns an empty sequence if the query datasource is unknown or there is matching result-level cache.
* Otherwise, it creates a sequence merging sequences from the regular broker cache and remote servers. If parallel
* merge is enabled, it can merge and *combine* the underlying sequences in parallel.
*
* @return a pair of a sequence merging results from remote query servers and the number of remote servers
* participating in query processing.
*/
ClusterQueryResult<T> run(
final UnaryOperator<TimelineLookup<String, ServerSelector>> timelineConverter,
final boolean specificSegments
)
{
final Optional<? extends TimelineLookup<String, ServerSelector>> maybeTimeline = serverView.getTimeline(
ev.getBaseTableDataSource()
);
if (!maybeTimeline.isPresent()) {
return new ClusterQueryResult<>(Sequences.empty(), 0);
}
final TimelineLookup<String, ServerSelector> timeline = timelineConverter.apply(maybeTimeline.get());
if (uncoveredIntervalsLimit > 0) {
computeUncoveredIntervals(timeline);
}
final Set<SegmentServerSelector> segmentServers = computeSegmentsToQuery(timeline, specificSegments);
final CloneQueryMode cloneQueryMode = query.context().getCloneQueryMode();
@Nullable
final byte[] queryCacheKey = cacheKeyManager.computeSegmentLevelQueryCacheKey();
@Nullable
final String prevEtag = (String) query.getContext().get(QueryResource.HEADER_IF_NONE_MATCH);
if (prevEtag != null) {
@Nullable
final String currentEtag = cacheKeyManager.computeResultLevelCachingEtag(segmentServers, cloneQueryMode, queryCacheKey);
if (null != currentEtag) {
responseContext.putEntityTag(currentEtag);
}
if (currentEtag != null && currentEtag.equals(prevEtag)) {
return new ClusterQueryResult<>(Sequences.empty(), 0);
}
}
final List<Pair<Interval, byte[]>> alreadyCachedResults =
pruneSegmentsWithCachedResults(queryCacheKey, segmentServers);
query = scheduler.prioritizeAndLaneQuery(queryPlus, segmentServers);
queryPlus = queryPlus.withQuery(query);
queryPlus = queryPlus.withQueryMetrics(toolChest);
queryPlus.getQueryMetrics().reportQueriedSegmentCount(segmentServers.size()).emit(emitter);
final SortedMap<DruidServer, List<SegmentDescriptor>> segmentsByServer = groupSegmentsByServer(
segmentServers,
cloneQueryMode
);
LazySequence<T> mergedResultSequence = new LazySequence<>(() -> {
List<Sequence<T>> sequencesByInterval = new ArrayList<>(alreadyCachedResults.size() + segmentsByServer.size());
addSequencesFromCache(sequencesByInterval, alreadyCachedResults);
addSequencesFromServer(sequencesByInterval, segmentsByServer);
return merge(sequencesByInterval);
});
return new ClusterQueryResult<>(scheduler.run(query, mergedResultSequence), segmentsByServer.size());
}
private Sequence<T> merge(List<Sequence<T>> sequencesByInterval)
{
BinaryOperator<T> mergeFn = toolChest.createMergeFn(query);
final QueryContext queryContext = query.context();
if (parallelMergeConfig.useParallelMergePool() && queryContext.getEnableParallelMerges() && mergeFn != null) {
final ParallelMergeCombiningSequence<T> parallelSequence = new ParallelMergeCombiningSequence<>(
pool,
sequencesByInterval,
query.getResultOrdering(),
mergeFn,
queryContext.hasTimeout(),
queryContext.getTimeout(),
queryContext.getPriority(),
queryContext.getParallelMergeParallelism(parallelMergeConfig.getDefaultMaxQueryParallelism()),
queryContext.getParallelMergeInitialYieldRows(parallelMergeConfig.getInitialYieldNumRows()),
queryContext.getParallelMergeSmallBatchRows(parallelMergeConfig.getSmallBatchNumRows()),
parallelMergeConfig.getTargetRunTimeMillis(),
reportMetrics -> {
QueryMetrics<?> queryMetrics = queryPlus.getQueryMetrics();
if (queryMetrics != null) {
queryMetrics.parallelMergeParallelism(reportMetrics.getParallelism());
queryMetrics.reportParallelMergeParallelism(reportMetrics.getParallelism()).emit(emitter);
queryMetrics.reportParallelMergeInputSequences(reportMetrics.getInputSequences()).emit(emitter);
queryMetrics.reportParallelMergeInputRows(reportMetrics.getInputRows()).emit(emitter);
queryMetrics.reportParallelMergeOutputRows(reportMetrics.getOutputRows()).emit(emitter);
queryMetrics.reportParallelMergeTaskCount(reportMetrics.getTaskCount()).emit(emitter);
queryMetrics.reportParallelMergeTotalCpuTime(reportMetrics.getTotalCpuTime()).emit(emitter);
queryMetrics.reportParallelMergeTotalTime(reportMetrics.getTotalTime()).emit(emitter);
queryMetrics.reportParallelMergeSlowestPartitionTime(reportMetrics.getSlowestPartitionInitializedTime())
.emit(emitter);
queryMetrics.reportParallelMergeFastestPartitionTime(reportMetrics.getFastestPartitionInitializedTime())
.emit(emitter);
}
}
);
scheduler.registerQueryFuture(query, parallelSequence.getCancellationFuture());
return parallelSequence;
} else {
return Sequences
.simple(sequencesByInterval)
.flatMerge(seq -> seq, query.getResultOrdering());
}
}
private Set<SegmentServerSelector> computeSegmentsToQuery(
TimelineLookup<String, ServerSelector> timeline,
boolean specificSegments
)
{
final java.util.function.Function<Interval, List<TimelineObjectHolder<String, ServerSelector>>> lookupFn
= specificSegments ? timeline::lookupWithIncompletePartitions : timeline::lookup;
List<TimelineObjectHolder<String, ServerSelector>> timelineObjectHolders =
intervals.stream().flatMap(i -> lookupFn.apply(i).stream()).collect(Collectors.toList());
final List<TimelineObjectHolder<String, ServerSelector>> serversLookup = toolChest.filterSegments(
query,
timelineObjectHolders
);
final Set<SegmentServerSelector> segments = new LinkedHashSet<>();
final Map<String, Optional<RangeSet<String>>> dimensionRangeCache;
final Set<String> filterFieldsForPruning;
final boolean trySecondaryPartititionPruning =
query.getFilter() != null && query.context().isSecondaryPartitionPruningEnabled();
if (trySecondaryPartititionPruning) {
dimensionRangeCache = new HashMap<>();
filterFieldsForPruning =
DimFilterUtils.onlyBaseFields(query.getFilter().getRequiredColumns(), ev::isBaseColumn);
} else {
dimensionRangeCache = null;
filterFieldsForPruning = null;
}
boolean isRealtimeSegmentOnly = query.context().isRealtimeSegmentsOnly();
// Filter unneeded chunks based on partition dimension
for (TimelineObjectHolder<String, ServerSelector> holder : serversLookup) {
final Set<PartitionChunk<ServerSelector>> filteredChunks;
if (trySecondaryPartititionPruning) {
filteredChunks = DimFilterUtils.filterShards(
query.getFilter(),
filterFieldsForPruning,
holder.getObject(),
partitionChunk -> partitionChunk.getObject().getSegment().getShardSpec(),
dimensionRangeCache
);
} else {
filteredChunks = Sets.newLinkedHashSet(holder.getObject());
}
for (PartitionChunk<ServerSelector> chunk : filteredChunks) {
ServerSelector server = chunk.getObject();
if (isRealtimeSegmentOnly && !server.isRealtimeSegment()) {
continue; // Skip historical segments when only realtime segments are requested
}
final SegmentDescriptor segment = new SegmentDescriptor(
holder.getInterval(),
holder.getVersion(),
chunk.getChunkNumber()
);
segments.add(new SegmentServerSelector(server, segment));
}
}
return segments;
}
private void computeUncoveredIntervals(TimelineLookup<String, ServerSelector> timeline)
{
final List<Interval> uncoveredIntervals = new ArrayList<>(uncoveredIntervalsLimit);
boolean uncoveredIntervalsOverflowed = false;
for (Interval interval : intervals) {
Iterable<TimelineObjectHolder<String, ServerSelector>> lookup = timeline.lookup(interval);
long startMillis = interval.getStartMillis();
long endMillis = interval.getEndMillis();
for (TimelineObjectHolder<String, ServerSelector> holder : lookup) {
Interval holderInterval = holder.getInterval();
long intervalStart = holderInterval.getStartMillis();
if (!uncoveredIntervalsOverflowed && startMillis != intervalStart) {
if (uncoveredIntervalsLimit > uncoveredIntervals.size()) {
uncoveredIntervals.add(Intervals.utc(startMillis, intervalStart));
} else {
uncoveredIntervalsOverflowed = true;
}
}
startMillis = holderInterval.getEndMillis();
}
if (!uncoveredIntervalsOverflowed && startMillis < endMillis) {
if (uncoveredIntervalsLimit > uncoveredIntervals.size()) {
uncoveredIntervals.add(Intervals.utc(startMillis, endMillis));
} else {
uncoveredIntervalsOverflowed = true;
}
}
}
if (!uncoveredIntervals.isEmpty()) {
// Record in the response context the interval for which NO segment is present.
// Which is not necessarily an indication that the data doesn't exist or is
// incomplete. The data could exist and just not be loaded yet. In either
// case, though, this query will not include any data from the identified intervals.
responseContext.putUncoveredIntervals(uncoveredIntervals, uncoveredIntervalsOverflowed);
}
}
private List<Pair<Interval, byte[]>> pruneSegmentsWithCachedResults(
final byte[] queryCacheKey,
final Set<SegmentServerSelector> segments
)
{
if (queryCacheKey == null) {
return Collections.emptyList();
}
final List<Pair<Interval, byte[]>> alreadyCachedResults = new ArrayList<>();
Map<SegmentServerSelector, Cache.NamedKey> perSegmentCacheKeys = computePerSegmentCacheKeys(
segments,
queryCacheKey
);
// Pull cached segments from cache and remove from set of segments to query
final Map<Cache.NamedKey, byte[]> cachedValues = computeCachedValues(perSegmentCacheKeys);
perSegmentCacheKeys.forEach((segment, segmentCacheKey) -> {
final Interval segmentQueryInterval = segment.getSegmentDescriptor().getInterval();
final byte[] cachedValue = cachedValues.get(segmentCacheKey);
if (cachedValue != null) {
// remove cached segment from set of segments to query
segments.remove(segment);
alreadyCachedResults.add(Pair.of(segmentQueryInterval, cachedValue));
} else if (populateCache) {
// otherwise, if populating cache, add segment to list of segments to cache
final SegmentId segmentId = segment.getServer().getSegment().getId();
addCachePopulatorKey(segmentCacheKey, segmentId, segmentQueryInterval);
}
});
return alreadyCachedResults;
}
private Map<SegmentServerSelector, Cache.NamedKey> computePerSegmentCacheKeys(
Set<SegmentServerSelector> segments,
byte[] queryCacheKey
)
{
// cacheKeys map must preserve segment ordering, in order for shards to always be combined in the same order
Map<SegmentServerSelector, Cache.NamedKey> cacheKeys = Maps.newLinkedHashMap();
for (SegmentServerSelector segmentServer : segments) {
final Cache.NamedKey segmentCacheKey = CacheUtil.computeSegmentCacheKey(
segmentServer.getServer().getSegment().getId().toString(),
segmentServer.getSegmentDescriptor(),
queryCacheKey
);
cacheKeys.put(segmentServer, segmentCacheKey);
}
return cacheKeys;
}
private Map<Cache.NamedKey, byte[]> computeCachedValues(Map<SegmentServerSelector, Cache.NamedKey> cacheKeys)
{
if (useCache) {
return cache.getBulk(Iterables.limit(cacheKeys.values(), cacheConfig.getCacheBulkMergeLimit()));
} else {
return ImmutableMap.of();
}
}
private void addCachePopulatorKey(
Cache.NamedKey segmentCacheKey,
SegmentId segmentId,
Interval segmentQueryInterval
)
{
cachePopulatorKeyMap.put(StringUtils.format("%s_%s", segmentId, segmentQueryInterval), segmentCacheKey);
}
@Nullable
private Cache.NamedKey getCachePopulatorKey(String segmentId, Interval segmentInterval)
{
return cachePopulatorKeyMap.get(StringUtils.format("%s_%s", segmentId, segmentInterval));
}
private SortedMap<DruidServer, List<SegmentDescriptor>> groupSegmentsByServer(
Set<SegmentServerSelector> segments,
CloneQueryMode cloneQueryMode
)
{
final SortedMap<DruidServer, List<SegmentDescriptor>> serverSegments = new TreeMap<>();
for (SegmentServerSelector segmentServer : segments) {
final QueryableDruidServer queryableDruidServer = segmentServer.getServer()
.pick(query, cloneQueryMode);
if (queryableDruidServer == null) {
log.makeAlert(
"No servers found for SegmentDescriptor[%s] for DataSource[%s]?! How can this be?!",
segmentServer.getSegmentDescriptor(),
query.getDataSource()
).emit();
} else {
final DruidServer server = queryableDruidServer.getServer();
serverSegments.computeIfAbsent(server, s -> new ArrayList<>()).add(segmentServer.getSegmentDescriptor());
}
}
return serverSegments;
}
private void addSequencesFromCache(
final List<Sequence<T>> listOfSequences,
final List<Pair<Interval, byte[]>> cachedResults
)
{
if (strategy == null) {
return;
}
final Function<Object, T> pullFromCacheFunction = strategy.pullFromSegmentLevelCache();
final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz();
for (Pair<Interval, byte[]> cachedResultPair : cachedResults) {
final byte[] cachedResult = cachedResultPair.rhs;
Sequence<Object> cachedSequence = new BaseSequence<>(
new BaseSequence.IteratorMaker<>()
{
@Override
public Iterator<Object> make()
{
try {
if (cachedResult.length == 0) {
return Collections.emptyIterator();
}
return objectMapper.readValues(
objectMapper.getFactory().createParser(cachedResult),
cacheObjectClazz
);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void cleanup(Iterator<Object> iterFromMake)
{
}
}
);
listOfSequences.add(Sequences.map(cachedSequence, pullFromCacheFunction));
}
}
/**
* Create sequences that reads from remote query servers (historicals and tasks). Note that the broker will
* hold an HTTP connection per server after this method is called.
*/
private void addSequencesFromServer(
final List<Sequence<T>> listOfSequences,
final SortedMap<DruidServer, List<SegmentDescriptor>> segmentsByServer
)
{
segmentsByServer.forEach((server, segmentsOfServer) -> {
final QueryRunner serverRunner = serverView.getQueryRunner(server);
if (serverRunner == null) {
log.error("Server [%s] doesn't have a query runner", server.getName());
return;
}
// Divide user-provided maxQueuedBytes by the number of servers, and limit each server to that much.
final long maxQueuedBytes = query.context().getMaxQueuedBytes(httpClientConfig.getMaxQueuedBytes());
final long maxQueuedBytesPerServer = maxQueuedBytes / segmentsByServer.size();
final Sequence<T> serverResults;
if (isBySegment) {
serverResults = getBySegmentServerResults(serverRunner, segmentsOfServer, maxQueuedBytesPerServer);
} else if (!server.isSegmentReplicationTarget() || !populateCache) {
serverResults = getSimpleServerResults(serverRunner, segmentsOfServer, maxQueuedBytesPerServer);
} else {
serverResults = getAndCacheServerResults(serverRunner, segmentsOfServer, maxQueuedBytesPerServer);
}
listOfSequences.add(serverResults);
});
}
@SuppressWarnings("unchecked")
private Sequence<T> getBySegmentServerResults(
final QueryRunner serverRunner,
final List<SegmentDescriptor> segmentsOfServer,
long maxQueuedBytesPerServer
)
{
Sequence<Result<BySegmentResultValueClass<T>>> resultsBySegments = serverRunner
.run(
queryPlus.withQuery(
Queries.withSpecificSegments(queryPlus.getQuery(), segmentsOfServer)
).withMaxQueuedBytes(maxQueuedBytesPerServer),
responseContext
);
// bySegment results need to be de-serialized, see DirectDruidClient.run()
return (Sequence<T>) resultsBySegments
.map(result -> result.map(
resultsOfSegment -> resultsOfSegment.mapResults(
toolChest.makePreComputeManipulatorFn(query, MetricManipulatorFns.deserializing())::apply
)
));
}
@SuppressWarnings("unchecked")
private Sequence<T> getSimpleServerResults(
final QueryRunner serverRunner,
final List<SegmentDescriptor> segmentsOfServer,
long maxQueuedBytesPerServer
)
{
return serverRunner.run(
queryPlus.withQuery(
Queries.withSpecificSegments(queryPlus.getQuery(), segmentsOfServer)
).withMaxQueuedBytes(maxQueuedBytesPerServer),
responseContext
);
}
private Sequence<T> getAndCacheServerResults(
final QueryRunner serverRunner,
final List<SegmentDescriptor> segmentsOfServer,
long maxQueuedBytesPerServer
)
{
@SuppressWarnings("unchecked")
final Query<T> downstreamQuery = query.withOverriddenContext(makeDownstreamQueryContext());
final Sequence<Result<BySegmentResultValueClass<T>>> resultsBySegments = serverRunner.run(
queryPlus
.withQuery(
Queries.withSpecificSegments(
downstreamQuery,
segmentsOfServer
)
)
.withMaxQueuedBytes(maxQueuedBytesPerServer),
responseContext
);
final Function<T, Object> cacheFn = strategy.prepareForSegmentLevelCache();
return resultsBySegments
.map(result -> {
final BySegmentResultValueClass<T> resultsOfSegment = result.getValue();
final Cache.NamedKey cachePopulatorKey =
getCachePopulatorKey(resultsOfSegment.getSegmentId(), resultsOfSegment.getInterval());
Sequence<T> res = Sequences.simple(resultsOfSegment.getResults());
if (cachePopulatorKey != null) {
res = cachePopulator.wrap(res, cacheFn::apply, cache, cachePopulatorKey);
}
return res.map(
toolChest.makePreComputeManipulatorFn(downstreamQuery, MetricManipulatorFns.deserializing())::apply
);
})
.flatMerge(seq -> seq, query.getResultOrdering());
}
}
/**
* An inner class that is used solely for computing cache keys. Its a separate class to allow extensive unit testing
* of cache key generation.
*/
@VisibleForTesting
static class CacheKeyManager<T>
{
private final Query<T> query;
private final CacheStrategy<T, Object, Query<T>> strategy;
private final boolean isSegmentLevelCachingEnable;
CacheKeyManager(
final Query<T> query,
final CacheStrategy<T, Object, Query<T>> strategy,
final boolean useCache,
final boolean populateCache
)
{
this.query = query;
this.strategy = strategy;
this.isSegmentLevelCachingEnable = ((populateCache || useCache)
&& !query.context().isBySegment()); // explicit bySegment queries are never cached
}
@Nullable
byte[] computeSegmentLevelQueryCacheKey()
{
if (isSegmentLevelCachingEnable) {
return computeQueryCacheKeyWithJoin();
}
return null;
}
/**
* It computes the ETAG which is used by {@link org.apache.druid.query.ResultLevelCachingQueryRunner} for
* result level caches. queryCacheKey can be null if segment level cache is not being used. However, ETAG
* is still computed since result level cache may still be on.
*/
@Nullable
String computeResultLevelCachingEtag(
final Set<SegmentServerSelector> segments,
final CloneQueryMode cloneQueryMode,
@Nullable byte[] queryCacheKey
)
{
Hasher hasher = Hashing.sha1().newHasher();
boolean hasOnlyHistoricalSegments = true;
for (SegmentServerSelector p : segments) {
QueryableDruidServer queryableServer = p.getServer().pick(query, cloneQueryMode);
if (queryableServer == null || !queryableServer.getServer().isSegmentReplicationTarget()) {
hasOnlyHistoricalSegments = false;
break;
}
hasher.putString(p.getServer().getSegment().getId().toString(), StandardCharsets.UTF_8);
// it is important to add the "query interval" as part ETag calculation
// to have result level cache work correctly for queries with different
// intervals covering the same set of segments
hasher.putString(p.rhs.getInterval().toString(), StandardCharsets.UTF_8);
}
if (!hasOnlyHistoricalSegments) {
return null;
}
// query cache key can be null if segment level caching is disabled
final byte[] queryCacheKeyFinal = (queryCacheKey == null) ? computeQueryCacheKeyWithJoin() : queryCacheKey;
if (queryCacheKeyFinal == null) {
return null;
}
hasher.putBytes(queryCacheKeyFinal);
String currEtag = StringUtils.encodeBase64String(hasher.hash().asBytes());
return currEtag;
}
/**
* Adds the cache key prefix for join data sources. Return null if its a join but caching is not supported
*/
@Nullable
private byte[] computeQueryCacheKeyWithJoin()
{
Preconditions.checkNotNull(strategy, "strategy cannot be null");
byte[] dataSourceCacheKey = query.getDataSource().getCacheKey();
if (null == dataSourceCacheKey) {
return null;
} else if (dataSourceCacheKey.length > 0) {
return Bytes.concat(dataSourceCacheKey, strategy.computeCacheKey(query));
} else {
return strategy.computeCacheKey(query);
}
}
}
/**
* Helper class to build a new timeline of filtered segments.
*/
public static class TimelineConverter<T extends Overshadowable<T>> implements UnaryOperator<TimelineLookup<String, T>>
{
private final Iterable<SegmentDescriptor> specs;
public TimelineConverter(final Iterable<SegmentDescriptor> specs)
{
this.specs = specs;
}
@Override
public TimelineLookup<String, T> apply(TimelineLookup<String, T> timeline)
{
Iterator<PartitionChunkEntry<String, T>> unfilteredIterator =
Iterators.transform(specs.iterator(), spec -> toChunkEntry(timeline, spec));
Iterator<PartitionChunkEntry<String, T>> iterator = Iterators.filter(
unfilteredIterator,
Objects::nonNull
);
final VersionedIntervalTimeline<String, T> newTimeline =
new VersionedIntervalTimeline<>(Ordering.natural(), true);
// VersionedIntervalTimeline#addAll implementation is much more efficient than calling VersionedIntervalTimeline#add
// in a loop when there are lot of segments to be added for same interval and version.
newTimeline.addAll(iterator);
return newTimeline;
}
@Nullable
private PartitionChunkEntry<String, T> toChunkEntry(
TimelineLookup<String, T> timeline,
SegmentDescriptor spec
)
{
PartitionChunk<T> chunk = timeline.findChunk(
spec.getInterval(),
spec.getVersion(),
spec.getPartitionNumber()
);
if (null == chunk) {
return null;
}
return new PartitionChunkEntry<>(spec.getInterval(), spec.getVersion(), chunk);
}
}
}
|
apache/hadoop-common | 37,998 | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobs.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.mapreduce.v2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.FailingMapper;
import org.apache.hadoop.RandomTextWriterJob;
import org.apache.hadoop.RandomTextWriterJob.RandomInputFormat;
import org.apache.hadoop.SleepJob;
import org.apache.hadoop.SleepJob.SleepMapper;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TaskLog;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobCounter;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.MRConfig;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskCompletionEvent;
import org.apache.hadoop.mapreduce.TaskID;
import org.apache.hadoop.mapreduce.TaskReport;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.TypeConverter;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.MRAppMaster;
import org.apache.hadoop.mapreduce.v2.app.speculate.DefaultSpeculator;
import org.apache.hadoop.mapreduce.v2.app.speculate.Speculator;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.ApplicationClassLoader;
import org.apache.hadoop.util.JarFinder;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.log4j.Level;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestMRJobs {
private static final Log LOG = LogFactory.getLog(TestMRJobs.class);
private static final EnumSet<RMAppState> TERMINAL_RM_APP_STATES =
EnumSet.of(RMAppState.FINISHED, RMAppState.FAILED, RMAppState.KILLED);
private static final int NUM_NODE_MGRS = 3;
private static final String TEST_IO_SORT_MB = "11";
protected static MiniMRYarnCluster mrCluster;
protected static MiniDFSCluster dfsCluster;
private static Configuration conf = new Configuration();
private static FileSystem localFs;
private static FileSystem remoteFs;
static {
try {
localFs = FileSystem.getLocal(conf);
} catch (IOException io) {
throw new RuntimeException("problem getting local fs", io);
}
}
private static Path TEST_ROOT_DIR = new Path("target",
TestMRJobs.class.getName() + "-tmpDir").makeQualified(localFs);
static Path APP_JAR = new Path(TEST_ROOT_DIR, "MRAppJar.jar");
private static final String OUTPUT_ROOT_DIR = "/tmp/" +
TestMRJobs.class.getSimpleName();
@BeforeClass
public static void setup() throws IOException {
try {
dfsCluster = new MiniDFSCluster.Builder(conf).numDataNodes(2)
.format(true).racks(null).build();
remoteFs = dfsCluster.getFileSystem();
} catch (IOException io) {
throw new RuntimeException("problem starting mini dfs cluster", io);
}
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
if (mrCluster == null) {
mrCluster = new MiniMRYarnCluster(TestMRJobs.class.getName(),
NUM_NODE_MGRS);
Configuration conf = new Configuration();
conf.set("fs.defaultFS", remoteFs.getUri().toString()); // use HDFS
conf.set(MRJobConfig.MR_AM_STAGING_DIR, "/apps_staging_dir");
mrCluster.init(conf);
mrCluster.start();
}
// Copy MRAppJar and make it private. TODO: FIXME. This is a hack to
// workaround the absent public discache.
localFs.copyFromLocalFile(new Path(MiniMRYarnCluster.APPJAR), APP_JAR);
localFs.setPermission(APP_JAR, new FsPermission("700"));
}
@AfterClass
public static void tearDown() {
if (mrCluster != null) {
mrCluster.stop();
mrCluster = null;
}
if (dfsCluster != null) {
dfsCluster.shutdown();
dfsCluster = null;
}
}
@Test (timeout = 300000)
public void testSleepJob() throws IOException, InterruptedException,
ClassNotFoundException {
LOG.info("\n\n\nStarting testSleepJob().");
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
Configuration sleepConf = new Configuration(mrCluster.getConfig());
// set master address to local to test that local mode applied iff framework == local
sleepConf.set(MRConfig.MASTER_ADDRESS, "local");
SleepJob sleepJob = new SleepJob();
sleepJob.setConf(sleepConf);
int numReduces = sleepConf.getInt("TestMRJobs.testSleepJob.reduces", 2); // or sleepConf.getConfig().getInt(MRJobConfig.NUM_REDUCES, 2);
// job with 3 maps (10s) and numReduces reduces (5s), 1 "record" each:
Job job = sleepJob.createJob(3, numReduces, 10000, 1, 5000, 1);
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.setJarByClass(SleepJob.class);
job.setMaxMapAttempts(1); // speed up failures
job.submit();
String trackingUrl = job.getTrackingURL();
String jobId = job.getJobID().toString();
boolean succeeded = job.waitForCompletion(true);
Assert.assertTrue(succeeded);
Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState());
Assert.assertTrue("Tracking URL was " + trackingUrl +
" but didn't Match Job ID " + jobId ,
trackingUrl.endsWith(jobId.substring(jobId.lastIndexOf("_")) + "/"));
verifySleepJobCounters(job);
verifyTaskProgress(job);
// TODO later: add explicit "isUber()" checks of some sort (extend
// JobStatus?)--compare against MRJobConfig.JOB_UBERTASK_ENABLE value
}
@Test(timeout = 300000)
public void testJobClassloader() throws IOException, InterruptedException,
ClassNotFoundException {
testJobClassloader(false);
}
@Test(timeout = 300000)
public void testJobClassloaderWithCustomClasses() throws IOException,
InterruptedException, ClassNotFoundException {
testJobClassloader(true);
}
private void testJobClassloader(boolean useCustomClasses) throws IOException,
InterruptedException, ClassNotFoundException {
LOG.info("\n\n\nStarting testJobClassloader()"
+ " useCustomClasses=" + useCustomClasses);
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
final Configuration sleepConf = new Configuration(mrCluster.getConfig());
// set master address to local to test that local mode applied iff framework == local
sleepConf.set(MRConfig.MASTER_ADDRESS, "local");
sleepConf.setBoolean(MRJobConfig.MAPREDUCE_JOB_CLASSLOADER, true);
if (useCustomClasses) {
// to test AM loading user classes such as output format class, we want
// to blacklist them from the system classes (they need to be prepended
// as the first match wins)
String systemClasses = ApplicationClassLoader.DEFAULT_SYSTEM_CLASSES;
// exclude the custom classes from system classes
systemClasses = "-" + CustomOutputFormat.class.getName() + ",-" +
CustomSpeculator.class.getName() + "," +
systemClasses;
sleepConf.set(MRJobConfig.MAPREDUCE_JOB_CLASSLOADER_SYSTEM_CLASSES,
systemClasses);
}
sleepConf.set(MRJobConfig.IO_SORT_MB, TEST_IO_SORT_MB);
sleepConf.set(MRJobConfig.MR_AM_LOG_LEVEL, Level.ALL.toString());
sleepConf.set(MRJobConfig.MAP_LOG_LEVEL, Level.ALL.toString());
sleepConf.set(MRJobConfig.REDUCE_LOG_LEVEL, Level.ALL.toString());
sleepConf.set(MRJobConfig.MAP_JAVA_OPTS, "-verbose:class");
final SleepJob sleepJob = new SleepJob();
sleepJob.setConf(sleepConf);
final Job job = sleepJob.createJob(1, 1, 10, 1, 10, 1);
job.setMapperClass(ConfVerificationMapper.class);
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.setJarByClass(SleepJob.class);
job.setMaxMapAttempts(1); // speed up failures
if (useCustomClasses) {
// set custom output format class and speculator class
job.setOutputFormatClass(CustomOutputFormat.class);
final Configuration jobConf = job.getConfiguration();
jobConf.setClass(MRJobConfig.MR_AM_JOB_SPECULATOR, CustomSpeculator.class,
Speculator.class);
// speculation needs to be enabled for the speculator to be loaded
jobConf.setBoolean(MRJobConfig.MAP_SPECULATIVE, true);
}
job.submit();
boolean succeeded = job.waitForCompletion(true);
Assert.assertTrue("Job status: " + job.getStatus().getFailureInfo(),
succeeded);
}
public static class CustomOutputFormat<K,V> extends NullOutputFormat<K,V> {
public CustomOutputFormat() {
verifyClassLoader(getClass());
}
/**
* Verifies that the class was loaded by the job classloader if it is in the
* context of the MRAppMaster, and if not throws an exception to fail the
* job.
*/
private void verifyClassLoader(Class<?> cls) {
// to detect that it is instantiated in the context of the MRAppMaster, we
// inspect the stack trace and determine a caller is MRAppMaster
for (StackTraceElement e: new Throwable().getStackTrace()) {
if (e.getClassName().equals(MRAppMaster.class.getName()) &&
!(cls.getClassLoader() instanceof ApplicationClassLoader)) {
throw new ExceptionInInitializerError("incorrect classloader used");
}
}
}
}
public static class CustomSpeculator extends DefaultSpeculator {
public CustomSpeculator(Configuration conf, AppContext context) {
super(conf, context);
verifyClassLoader(getClass());
}
/**
* Verifies that the class was loaded by the job classloader if it is in the
* context of the MRAppMaster, and if not throws an exception to fail the
* job.
*/
private void verifyClassLoader(Class<?> cls) {
// to detect that it is instantiated in the context of the MRAppMaster, we
// inspect the stack trace and determine a caller is MRAppMaster
for (StackTraceElement e: new Throwable().getStackTrace()) {
if (e.getClassName().equals(MRAppMaster.class.getName()) &&
!(cls.getClassLoader() instanceof ApplicationClassLoader)) {
throw new ExceptionInInitializerError("incorrect classloader used");
}
}
}
}
protected void verifySleepJobCounters(Job job) throws InterruptedException,
IOException {
Counters counters = job.getCounters();
Assert.assertEquals(3, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS)
.getValue());
Assert.assertEquals(3, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS)
.getValue());
Assert.assertEquals(2,
counters.findCounter(JobCounter.TOTAL_LAUNCHED_REDUCES).getValue());
Assert
.assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null
&& counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0);
Assert
.assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null
&& counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0);
}
protected void verifyTaskProgress(Job job) throws InterruptedException,
IOException {
for (TaskReport taskReport : job.getTaskReports(TaskType.MAP)) {
Assert.assertTrue(0.9999f < taskReport.getProgress()
&& 1.0001f > taskReport.getProgress());
}
for (TaskReport taskReport : job.getTaskReports(TaskType.REDUCE)) {
Assert.assertTrue(0.9999f < taskReport.getProgress()
&& 1.0001f > taskReport.getProgress());
}
}
@Test (timeout = 60000)
public void testRandomWriter() throws IOException, InterruptedException,
ClassNotFoundException {
LOG.info("\n\n\nStarting testRandomWriter().");
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
RandomTextWriterJob randomWriterJob = new RandomTextWriterJob();
mrCluster.getConfig().set(RandomTextWriterJob.TOTAL_BYTES, "3072");
mrCluster.getConfig().set(RandomTextWriterJob.BYTES_PER_MAP, "1024");
Job job = randomWriterJob.createJob(mrCluster.getConfig());
Path outputDir = new Path(OUTPUT_ROOT_DIR, "random-output");
FileOutputFormat.setOutputPath(job, outputDir);
job.setSpeculativeExecution(false);
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.setJarByClass(RandomTextWriterJob.class);
job.setMaxMapAttempts(1); // speed up failures
job.submit();
String trackingUrl = job.getTrackingURL();
String jobId = job.getJobID().toString();
boolean succeeded = job.waitForCompletion(true);
Assert.assertTrue(succeeded);
Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState());
Assert.assertTrue("Tracking URL was " + trackingUrl +
" but didn't Match Job ID " + jobId ,
trackingUrl.endsWith(jobId.substring(jobId.lastIndexOf("_")) + "/"));
// Make sure there are three files in the output-dir
RemoteIterator<FileStatus> iterator =
FileContext.getFileContext(mrCluster.getConfig()).listStatus(
outputDir);
int count = 0;
while (iterator.hasNext()) {
FileStatus file = iterator.next();
if (!file.getPath().getName()
.equals(FileOutputCommitter.SUCCEEDED_FILE_NAME)) {
count++;
}
}
Assert.assertEquals("Number of part files is wrong!", 3, count);
verifyRandomWriterCounters(job);
// TODO later: add explicit "isUber()" checks of some sort
}
protected void verifyRandomWriterCounters(Job job)
throws InterruptedException, IOException {
Counters counters = job.getCounters();
Assert.assertEquals(3, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS)
.getValue());
Assert.assertEquals(3, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS)
.getValue());
Assert
.assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null
&& counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0);
}
@Test (timeout = 60000)
public void testFailingMapper() throws IOException, InterruptedException,
ClassNotFoundException {
LOG.info("\n\n\nStarting testFailingMapper().");
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
Job job = runFailingMapperJob();
TaskID taskID = new TaskID(job.getJobID(), TaskType.MAP, 0);
TaskAttemptID aId = new TaskAttemptID(taskID, 0);
System.out.println("Diagnostics for " + aId + " :");
for (String diag : job.getTaskDiagnostics(aId)) {
System.out.println(diag);
}
aId = new TaskAttemptID(taskID, 1);
System.out.println("Diagnostics for " + aId + " :");
for (String diag : job.getTaskDiagnostics(aId)) {
System.out.println(diag);
}
TaskCompletionEvent[] events = job.getTaskCompletionEvents(0, 2);
Assert.assertEquals(TaskCompletionEvent.Status.FAILED,
events[0].getStatus());
Assert.assertEquals(TaskCompletionEvent.Status.TIPFAILED,
events[1].getStatus());
Assert.assertEquals(JobStatus.State.FAILED, job.getJobState());
verifyFailingMapperCounters(job);
// TODO later: add explicit "isUber()" checks of some sort
}
protected void verifyFailingMapperCounters(Job job)
throws InterruptedException, IOException {
Counters counters = job.getCounters();
Assert.assertEquals(2, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS)
.getValue());
Assert.assertEquals(2, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS)
.getValue());
Assert.assertEquals(2, counters.findCounter(JobCounter.NUM_FAILED_MAPS)
.getValue());
Assert
.assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null
&& counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0);
}
protected Job runFailingMapperJob()
throws IOException, InterruptedException, ClassNotFoundException {
Configuration myConf = new Configuration(mrCluster.getConfig());
myConf.setInt(MRJobConfig.NUM_MAPS, 1);
myConf.setInt(MRJobConfig.MAP_MAX_ATTEMPTS, 2); //reduce the number of attempts
Job job = new Job(myConf);
job.setJarByClass(FailingMapper.class);
job.setJobName("failmapper");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(RandomInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapperClass(FailingMapper.class);
job.setNumReduceTasks(0);
FileOutputFormat.setOutputPath(job, new Path(OUTPUT_ROOT_DIR,
"failmapper-output"));
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.submit();
String trackingUrl = job.getTrackingURL();
String jobId = job.getJobID().toString();
boolean succeeded = job.waitForCompletion(true);
Assert.assertFalse(succeeded);
Assert.assertTrue("Tracking URL was " + trackingUrl +
" but didn't Match Job ID " + jobId ,
trackingUrl.endsWith(jobId.substring(jobId.lastIndexOf("_")) + "/"));
return job;
}
//@Test (timeout = 60000)
public void testSleepJobWithSecurityOn() throws IOException,
InterruptedException, ClassNotFoundException {
LOG.info("\n\n\nStarting testSleepJobWithSecurityOn().");
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
return;
}
mrCluster.getConfig().set(
CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION,
"kerberos");
mrCluster.getConfig().set(YarnConfiguration.RM_KEYTAB, "/etc/krb5.keytab");
mrCluster.getConfig().set(YarnConfiguration.NM_KEYTAB, "/etc/krb5.keytab");
mrCluster.getConfig().set(YarnConfiguration.RM_PRINCIPAL,
"rm/sightbusy-lx@LOCALHOST");
mrCluster.getConfig().set(YarnConfiguration.NM_PRINCIPAL,
"nm/sightbusy-lx@LOCALHOST");
UserGroupInformation.setConfiguration(mrCluster.getConfig());
// Keep it in here instead of after RM/NM as multiple user logins happen in
// the same JVM.
UserGroupInformation user = UserGroupInformation.getCurrentUser();
LOG.info("User name is " + user.getUserName());
for (Token<? extends TokenIdentifier> str : user.getTokens()) {
LOG.info("Token is " + str.encodeToUrlString());
}
user.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
SleepJob sleepJob = new SleepJob();
sleepJob.setConf(mrCluster.getConfig());
Job job = sleepJob.createJob(3, 0, 10000, 1, 0, 0);
// //Job with reduces
// Job job = sleepJob.createJob(3, 2, 10000, 1, 10000, 1);
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.submit();
String trackingUrl = job.getTrackingURL();
String jobId = job.getJobID().toString();
job.waitForCompletion(true);
Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState());
Assert.assertTrue("Tracking URL was " + trackingUrl +
" but didn't Match Job ID " + jobId ,
trackingUrl.endsWith(jobId.substring(jobId.lastIndexOf("_")) + "/"));
return null;
}
});
// TODO later: add explicit "isUber()" checks of some sort
}
@Test(timeout = 120000)
public void testContainerRollingLog() throws IOException,
InterruptedException, ClassNotFoundException {
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
final SleepJob sleepJob = new SleepJob();
final JobConf sleepConf = new JobConf(mrCluster.getConfig());
sleepConf.set(MRJobConfig.MAP_LOG_LEVEL, Level.ALL.toString());
final long userLogKb = 4;
sleepConf.setLong(MRJobConfig.TASK_USERLOG_LIMIT, userLogKb);
sleepConf.setInt(MRJobConfig.TASK_LOG_BACKUPS, 3);
sleepConf.set(MRJobConfig.MR_AM_LOG_LEVEL, Level.ALL.toString());
final long amLogKb = 7;
sleepConf.setLong(MRJobConfig.MR_AM_LOG_KB, amLogKb);
sleepConf.setInt(MRJobConfig.MR_AM_LOG_BACKUPS, 7);
sleepJob.setConf(sleepConf);
final Job job = sleepJob.createJob(1, 0, 1L, 100, 0L, 0);
job.setJarByClass(SleepJob.class);
job.addFileToClassPath(APP_JAR); // The AppMaster jar itself.
job.waitForCompletion(true);
final JobId jobId = TypeConverter.toYarn(job.getJobID());
final ApplicationId appID = jobId.getAppId();
int pollElapsed = 0;
while (true) {
Thread.sleep(1000);
pollElapsed += 1000;
if (TERMINAL_RM_APP_STATES.contains(
mrCluster.getResourceManager().getRMContext().getRMApps().get(appID)
.getState())) {
break;
}
if (pollElapsed >= 60000) {
LOG.warn("application did not reach terminal state within 60 seconds");
break;
}
}
Assert.assertEquals(RMAppState.FINISHED, mrCluster.getResourceManager()
.getRMContext().getRMApps().get(appID).getState());
// Job finished, verify logs
//
final String appIdStr = appID.toString();
final String appIdSuffix = appIdStr.substring("application_".length(),
appIdStr.length());
final String containerGlob = "container_" + appIdSuffix + "_*_*";
final String syslogGlob = appIdStr
+ Path.SEPARATOR + containerGlob
+ Path.SEPARATOR + TaskLog.LogName.SYSLOG;
int numAppMasters = 0;
int numMapTasks = 0;
for (int i = 0; i < NUM_NODE_MGRS; i++) {
final Configuration nmConf = mrCluster.getNodeManager(i).getConfig();
for (String logDir :
nmConf.getTrimmedStrings(YarnConfiguration.NM_LOG_DIRS)) {
final Path absSyslogGlob =
new Path(logDir + Path.SEPARATOR + syslogGlob);
LOG.info("Checking for glob: " + absSyslogGlob);
final FileStatus[] syslogs = localFs.globStatus(absSyslogGlob);
for (FileStatus slog : syslogs) {
boolean foundAppMaster = job.isUber();
final Path containerPathComponent = slog.getPath().getParent();
if (!foundAppMaster) {
final ContainerId cid = ConverterUtils.toContainerId(
containerPathComponent.getName());
foundAppMaster = (cid.getId() == 1);
}
final FileStatus[] sysSiblings = localFs.globStatus(new Path(
containerPathComponent, TaskLog.LogName.SYSLOG + "*"));
// sort to ensure for i > 0 sysSiblings[i] == "syslog.i"
Arrays.sort(sysSiblings);
if (foundAppMaster) {
numAppMasters++;
} else {
numMapTasks++;
}
if (foundAppMaster) {
Assert.assertSame("Unexpected number of AM sylog* files",
sleepConf.getInt(MRJobConfig.MR_AM_LOG_BACKUPS, 0) + 1,
sysSiblings.length);
Assert.assertTrue("AM syslog.1 length kb should be >= " + amLogKb,
sysSiblings[1].getLen() >= amLogKb * 1024);
} else {
Assert.assertSame("Unexpected number of MR task sylog* files",
sleepConf.getInt(MRJobConfig.TASK_LOG_BACKUPS, 0) + 1,
sysSiblings.length);
Assert.assertTrue("MR syslog.1 length kb should be >= " + userLogKb,
sysSiblings[1].getLen() >= userLogKb * 1024);
}
}
}
}
// Make sure we checked non-empty set
//
Assert.assertEquals("No AppMaster log found!", 1, numAppMasters);
if (sleepConf.getBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, false)) {
Assert.assertEquals("MapTask log with uber found!", 0, numMapTasks);
} else {
Assert.assertEquals("No MapTask log found!", 1, numMapTasks);
}
}
public static class DistributedCacheChecker extends
Mapper<LongWritable, Text, NullWritable, NullWritable> {
@Override
public void setup(Context context) throws IOException {
Configuration conf = context.getConfiguration();
Path[] localFiles = context.getLocalCacheFiles();
URI[] files = context.getCacheFiles();
Path[] localArchives = context.getLocalCacheArchives();
URI[] archives = context.getCacheArchives();
// Check that 4 (2 + appjar + DistrubutedCacheChecker jar) files
// and 2 archives are present
Assert.assertEquals(4, localFiles.length);
Assert.assertEquals(4, files.length);
Assert.assertEquals(2, localArchives.length);
Assert.assertEquals(2, archives.length);
// Check lengths of the files
Map<String, Path> filesMap = pathsToMap(localFiles);
Assert.assertTrue(filesMap.containsKey("distributed.first.symlink"));
Assert.assertEquals(1, localFs.getFileStatus(
filesMap.get("distributed.first.symlink")).getLen());
Assert.assertTrue(filesMap.containsKey("distributed.second.jar"));
Assert.assertTrue(localFs.getFileStatus(
filesMap.get("distributed.second.jar")).getLen() > 1);
// Check extraction of the archive
Map<String, Path> archivesMap = pathsToMap(localArchives);
Assert.assertTrue(archivesMap.containsKey("distributed.third.jar"));
Assert.assertTrue(localFs.exists(new Path(
archivesMap.get("distributed.third.jar"), "distributed.jar.inside3")));
Assert.assertTrue(archivesMap.containsKey("distributed.fourth.jar"));
Assert.assertTrue(localFs.exists(new Path(
archivesMap.get("distributed.fourth.jar"), "distributed.jar.inside4")));
// Check the class loaders
LOG.info("Java Classpath: " + System.getProperty("java.class.path"));
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// Both the file and the archive should have been added to classpath, so
// both should be reachable via the class loader.
Assert.assertNotNull(cl.getResource("distributed.jar.inside2"));
Assert.assertNotNull(cl.getResource("distributed.jar.inside3"));
Assert.assertNotNull(cl.getResource("distributed.jar.inside4"));
// The Job Jar should have been extracted to a folder named "job.jar" and
// added to the classpath; the two jar files in the lib folder in the Job
// Jar should have also been added to the classpath
Assert.assertNotNull(cl.getResource("job.jar/"));
Assert.assertNotNull(cl.getResource("job.jar/lib/lib1.jar"));
Assert.assertNotNull(cl.getResource("job.jar/lib/lib2.jar"));
// Check that the symlink for the renaming was created in the cwd;
File symlinkFile = new File("distributed.first.symlink");
Assert.assertTrue(symlinkFile.exists());
Assert.assertEquals(1, symlinkFile.length());
// Check that the symlink for the Job Jar was created in the cwd and
// points to the extracted directory
File jobJarDir = new File("job.jar");
if (Shell.WINDOWS) {
Assert.assertTrue(isWindowsSymlinkedDirectory(jobJarDir));
} else {
Assert.assertTrue(FileUtils.isSymlink(jobJarDir));
Assert.assertTrue(jobJarDir.isDirectory());
}
}
/**
* Used on Windows to determine if the specified file is a symlink that
* targets a directory. On most platforms, these checks can be done using
* commons-io. On Windows, the commons-io implementation is unreliable and
* always returns false. Instead, this method checks the output of the dir
* command. After migrating to Java 7, this method can be removed in favor
* of the new method java.nio.file.Files.isSymbolicLink, which is expected to
* work cross-platform.
*
* @param file File to check
* @return boolean true if the file is a symlink that targets a directory
* @throws IOException thrown for any I/O error
*/
private static boolean isWindowsSymlinkedDirectory(File file)
throws IOException {
String dirOut = Shell.execCommand("cmd", "/c", "dir",
file.getAbsoluteFile().getParent());
StringReader sr = new StringReader(dirOut);
BufferedReader br = new BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
line = br.readLine();
if (line.contains(file.getName()) && line.contains("<SYMLINKD>")) {
return true;
}
}
return false;
} finally {
IOUtils.closeStream(br);
IOUtils.closeStream(sr);
}
}
/**
* Returns a mapping of the final component of each path to the corresponding
* Path instance. This assumes that every given Path has a unique string in
* the final path component, which is true for these tests.
*
* @param paths Path[] to map
* @return Map<String, Path> mapping the final component of each path to the
* corresponding Path instance
*/
private static Map<String, Path> pathsToMap(Path[] paths) {
Map<String, Path> map = new HashMap<String, Path>();
for (Path path: paths) {
map.put(path.getName(), path);
}
return map;
}
}
public void _testDistributedCache(String jobJarPath) throws Exception {
if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) {
LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR
+ " not found. Not running test.");
return;
}
// Create a temporary file of length 1.
Path first = createTempFile("distributed.first", "x");
// Create two jars with a single file inside them.
Path second =
makeJar(new Path(TEST_ROOT_DIR, "distributed.second.jar"), 2);
Path third =
makeJar(new Path(TEST_ROOT_DIR, "distributed.third.jar"), 3);
Path fourth =
makeJar(new Path(TEST_ROOT_DIR, "distributed.fourth.jar"), 4);
Job job = Job.getInstance(mrCluster.getConfig());
// Set the job jar to a new "dummy" jar so we can check that its extracted
// properly
job.setJar(jobJarPath);
// Because the job jar is a "dummy" jar, we need to include the jar with
// DistributedCacheChecker or it won't be able to find it
Path distributedCacheCheckerJar = new Path(
JarFinder.getJar(DistributedCacheChecker.class));
job.addFileToClassPath(distributedCacheCheckerJar.makeQualified(
localFs.getUri(), distributedCacheCheckerJar.getParent()));
job.setMapperClass(DistributedCacheChecker.class);
job.setOutputFormatClass(NullOutputFormat.class);
FileInputFormat.setInputPaths(job, first);
// Creates the Job Configuration
job.addCacheFile(
new URI(first.toUri().toString() + "#distributed.first.symlink"));
job.addFileToClassPath(second);
// The AppMaster jar itself
job.addFileToClassPath(
APP_JAR.makeQualified(localFs.getUri(), APP_JAR.getParent()));
job.addArchiveToClassPath(third);
job.addCacheArchive(fourth.toUri());
job.setMaxMapAttempts(1); // speed up failures
job.submit();
String trackingUrl = job.getTrackingURL();
String jobId = job.getJobID().toString();
Assert.assertTrue(job.waitForCompletion(false));
Assert.assertTrue("Tracking URL was " + trackingUrl +
" but didn't Match Job ID " + jobId ,
trackingUrl.endsWith(jobId.substring(jobId.lastIndexOf("_")) + "/"));
}
@Test (timeout = 600000)
public void testDistributedCache() throws Exception {
// Test with a local (file:///) Job Jar
Path localJobJarPath = makeJobJarWithLib(TEST_ROOT_DIR.toUri().toString());
_testDistributedCache(localJobJarPath.toUri().toString());
// Test with a remote (hdfs://) Job Jar
Path remoteJobJarPath = new Path(remoteFs.getUri().toString() + "/",
localJobJarPath.getName());
remoteFs.moveFromLocalFile(localJobJarPath, remoteJobJarPath);
File localJobJarFile = new File(localJobJarPath.toUri().toString());
if (localJobJarFile.exists()) { // just to make sure
localJobJarFile.delete();
}
_testDistributedCache(remoteJobJarPath.toUri().toString());
}
private Path createTempFile(String filename, String contents)
throws IOException {
Path path = new Path(TEST_ROOT_DIR, filename);
FSDataOutputStream os = localFs.create(path);
os.writeBytes(contents);
os.close();
localFs.setPermission(path, new FsPermission("700"));
return path;
}
private Path makeJar(Path p, int index) throws FileNotFoundException,
IOException {
FileOutputStream fos =
new FileOutputStream(new File(p.toUri().getPath()));
JarOutputStream jos = new JarOutputStream(fos);
ZipEntry ze = new ZipEntry("distributed.jar.inside" + index);
jos.putNextEntry(ze);
jos.write(("inside the jar!" + index).getBytes());
jos.closeEntry();
jos.close();
localFs.setPermission(p, new FsPermission("700"));
return p;
}
private Path makeJobJarWithLib(String testDir) throws FileNotFoundException,
IOException{
Path jobJarPath = new Path(testDir, "thejob.jar");
FileOutputStream fos =
new FileOutputStream(new File(jobJarPath.toUri().getPath()));
JarOutputStream jos = new JarOutputStream(fos);
// Have to put in real jar files or it will complain
createAndAddJarToJar(jos, new File(
new Path(testDir, "lib1.jar").toUri().getPath()));
createAndAddJarToJar(jos, new File(
new Path(testDir, "lib2.jar").toUri().getPath()));
jos.close();
localFs.setPermission(jobJarPath, new FsPermission("700"));
return jobJarPath;
}
private void createAndAddJarToJar(JarOutputStream jos, File jarFile)
throws FileNotFoundException, IOException {
FileOutputStream fos2 = new FileOutputStream(jarFile);
JarOutputStream jos2 = new JarOutputStream(fos2);
// Have to have at least one entry or it will complain
ZipEntry ze = new ZipEntry("lib1.inside");
jos2.putNextEntry(ze);
jos2.closeEntry();
jos2.close();
ze = new ZipEntry("lib/" + jarFile.getName());
jos.putNextEntry(ze);
FileInputStream in = new FileInputStream(jarFile);
byte buf[] = new byte[1024];
int numRead;
do {
numRead = in.read(buf);
if (numRead >= 0) {
jos.write(buf, 0, numRead);
}
} while (numRead != -1);
in.close();
jos.closeEntry();
jarFile.delete();
}
public static class ConfVerificationMapper extends SleepMapper {
@Override
protected void setup(Context context)
throws IOException, InterruptedException {
super.setup(context);
final Configuration conf = context.getConfiguration();
final String ioSortMb = conf.get(MRJobConfig.IO_SORT_MB);
if (!TEST_IO_SORT_MB.equals(ioSortMb)) {
throw new IOException("io.sort.mb expected: " + TEST_IO_SORT_MB
+ ", actual: " + ioSortMb);
}
}
}
}
|
googleads/google-ads-java | 38,221 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/MutateCustomerRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/services/customer_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.services;
/**
* <pre>
* Request message for
* [CustomerService.MutateCustomer][google.ads.googleads.v19.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.MutateCustomerRequest}
*/
public final class MutateCustomerRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.MutateCustomerRequest)
MutateCustomerRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateCustomerRequest.newBuilder() to construct.
private MutateCustomerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateCustomerRequest() {
customerId_ = "";
responseContentType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateCustomerRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.CustomerServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.CustomerServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.MutateCustomerRequest.class, com.google.ads.googleads.v19.services.MutateCustomerRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 4;
private com.google.ads.googleads.v19.services.CustomerOperation operation_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v19.services.CustomerOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v19.services.CustomerOperation.getDefaultInstance() : operation_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 5;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 6;
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override public com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getOperation());
}
if (validateOnly_ != false) {
output.writeBool(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
output.writeEnum(6, responseContentType_);
}
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(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getOperation());
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(6, responseContentType_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.services.MutateCustomerRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.services.MutateCustomerRequest other = (com.google.ads.googleads.v19.services.MutateCustomerRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getValidateOnly()
!= other.getValidateOnly()) return false;
if (responseContentType_ != other.responseContentType_) 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) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getValidateOnly());
hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER;
hash = (53 * hash) + responseContentType_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.services.MutateCustomerRequest 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
* [CustomerService.MutateCustomer][google.ads.googleads.v19.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.MutateCustomerRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.MutateCustomerRequest)
com.google.ads.googleads.v19.services.MutateCustomerRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.CustomerServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.CustomerServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.MutateCustomerRequest.class, com.google.ads.googleads.v19.services.MutateCustomerRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v19.services.MutateCustomerRequest.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;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
validateOnly_ = false;
responseContentType_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.services.CustomerServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateCustomerRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v19.services.MutateCustomerRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateCustomerRequest build() {
com.google.ads.googleads.v19.services.MutateCustomerRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateCustomerRequest buildPartial() {
com.google.ads.googleads.v19.services.MutateCustomerRequest result = new com.google.ads.googleads.v19.services.MutateCustomerRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.services.MutateCustomerRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
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.validateOnly_ = validateOnly_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.responseContentType_ = responseContentType_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v19.services.MutateCustomerRequest) {
return mergeFrom((com.google.ads.googleads.v19.services.MutateCustomerRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.services.MutateCustomerRequest other) {
if (other == com.google.ads.googleads.v19.services.MutateCustomerRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
if (other.responseContentType_ != 0) {
setResponseContentTypeValue(other.getResponseContentTypeValue());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 34: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 40: {
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 40
case 48: {
responseContentType_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 48
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v19.services.CustomerOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.CustomerOperation, com.google.ads.googleads.v19.services.CustomerOperation.Builder, com.google.ads.googleads.v19.services.CustomerOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v19.services.CustomerOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v19.services.CustomerOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v19.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v19.services.CustomerOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v19.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v19.services.CustomerOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.services.CustomerOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.services.CustomerOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v19.services.CustomerOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v19.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.CustomerOperation, com.google.ads.googleads.v19.services.CustomerOperation.Builder, com.google.ads.googleads.v19.services.CustomerOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.CustomerOperation, com.google.ads.googleads.v19.services.CustomerOperation.Builder, com.google.ads.googleads.v19.services.CustomerOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</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, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The enum numeric value on the wire for responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentTypeValue(int value) {
responseContentType_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override
public com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentType(com.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
responseContentType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return This builder for chaining.
*/
public Builder clearResponseContentType() {
bitField0_ = (bitField0_ & ~0x00000008);
responseContentType_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.services.MutateCustomerRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.MutateCustomerRequest)
private static final com.google.ads.googleads.v19.services.MutateCustomerRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.MutateCustomerRequest();
}
public static com.google.ads.googleads.v19.services.MutateCustomerRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateCustomerRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateCustomerRequest>() {
@java.lang.Override
public MutateCustomerRequest 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<MutateCustomerRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateCustomerRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateCustomerRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 38,221 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/MutateCustomerRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/services/customer_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.services;
/**
* <pre>
* Request message for
* [CustomerService.MutateCustomer][google.ads.googleads.v20.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.MutateCustomerRequest}
*/
public final class MutateCustomerRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.MutateCustomerRequest)
MutateCustomerRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateCustomerRequest.newBuilder() to construct.
private MutateCustomerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateCustomerRequest() {
customerId_ = "";
responseContentType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateCustomerRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.CustomerServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.CustomerServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.MutateCustomerRequest.class, com.google.ads.googleads.v20.services.MutateCustomerRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 4;
private com.google.ads.googleads.v20.services.CustomerOperation operation_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v20.services.CustomerOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v20.services.CustomerOperation.getDefaultInstance() : operation_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 5;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 6;
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override public com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getOperation());
}
if (validateOnly_ != false) {
output.writeBool(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
output.writeEnum(6, responseContentType_);
}
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(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getOperation());
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(6, responseContentType_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.services.MutateCustomerRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.services.MutateCustomerRequest other = (com.google.ads.googleads.v20.services.MutateCustomerRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getValidateOnly()
!= other.getValidateOnly()) return false;
if (responseContentType_ != other.responseContentType_) 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) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getValidateOnly());
hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER;
hash = (53 * hash) + responseContentType_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.services.MutateCustomerRequest 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
* [CustomerService.MutateCustomer][google.ads.googleads.v20.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.MutateCustomerRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.MutateCustomerRequest)
com.google.ads.googleads.v20.services.MutateCustomerRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.CustomerServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.CustomerServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.MutateCustomerRequest.class, com.google.ads.googleads.v20.services.MutateCustomerRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v20.services.MutateCustomerRequest.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;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
validateOnly_ = false;
responseContentType_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.services.CustomerServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateCustomerRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v20.services.MutateCustomerRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateCustomerRequest build() {
com.google.ads.googleads.v20.services.MutateCustomerRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateCustomerRequest buildPartial() {
com.google.ads.googleads.v20.services.MutateCustomerRequest result = new com.google.ads.googleads.v20.services.MutateCustomerRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.services.MutateCustomerRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
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.validateOnly_ = validateOnly_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.responseContentType_ = responseContentType_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v20.services.MutateCustomerRequest) {
return mergeFrom((com.google.ads.googleads.v20.services.MutateCustomerRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.services.MutateCustomerRequest other) {
if (other == com.google.ads.googleads.v20.services.MutateCustomerRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
if (other.responseContentType_ != 0) {
setResponseContentTypeValue(other.getResponseContentTypeValue());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 34: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 40: {
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 40
case 48: {
responseContentType_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 48
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v20.services.CustomerOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.CustomerOperation, com.google.ads.googleads.v20.services.CustomerOperation.Builder, com.google.ads.googleads.v20.services.CustomerOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v20.services.CustomerOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v20.services.CustomerOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v20.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v20.services.CustomerOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v20.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v20.services.CustomerOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.services.CustomerOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.services.CustomerOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v20.services.CustomerOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v20.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.CustomerOperation, com.google.ads.googleads.v20.services.CustomerOperation.Builder, com.google.ads.googleads.v20.services.CustomerOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.CustomerOperation, com.google.ads.googleads.v20.services.CustomerOperation.Builder, com.google.ads.googleads.v20.services.CustomerOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</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, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The enum numeric value on the wire for responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentTypeValue(int value) {
responseContentType_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override
public com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentType(com.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
responseContentType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return This builder for chaining.
*/
public Builder clearResponseContentType() {
bitField0_ = (bitField0_ & ~0x00000008);
responseContentType_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.services.MutateCustomerRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.MutateCustomerRequest)
private static final com.google.ads.googleads.v20.services.MutateCustomerRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.MutateCustomerRequest();
}
public static com.google.ads.googleads.v20.services.MutateCustomerRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateCustomerRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateCustomerRequest>() {
@java.lang.Override
public MutateCustomerRequest 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<MutateCustomerRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateCustomerRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateCustomerRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 38,221 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/MutateCustomerRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/services/customer_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.services;
/**
* <pre>
* Request message for
* [CustomerService.MutateCustomer][google.ads.googleads.v21.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.MutateCustomerRequest}
*/
public final class MutateCustomerRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.MutateCustomerRequest)
MutateCustomerRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateCustomerRequest.newBuilder() to construct.
private MutateCustomerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateCustomerRequest() {
customerId_ = "";
responseContentType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateCustomerRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.CustomerServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.CustomerServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.MutateCustomerRequest.class, com.google.ads.googleads.v21.services.MutateCustomerRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 4;
private com.google.ads.googleads.v21.services.CustomerOperation operation_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v21.services.CustomerOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v21.services.CustomerOperation.getDefaultInstance() : operation_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 5;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 6;
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override public com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getOperation());
}
if (validateOnly_ != false) {
output.writeBool(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
output.writeEnum(6, responseContentType_);
}
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(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getOperation());
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(5, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(6, responseContentType_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.services.MutateCustomerRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.services.MutateCustomerRequest other = (com.google.ads.googleads.v21.services.MutateCustomerRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getValidateOnly()
!= other.getValidateOnly()) return false;
if (responseContentType_ != other.responseContentType_) 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) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getValidateOnly());
hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER;
hash = (53 * hash) + responseContentType_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.services.MutateCustomerRequest 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
* [CustomerService.MutateCustomer][google.ads.googleads.v21.services.CustomerService.MutateCustomer].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.MutateCustomerRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.MutateCustomerRequest)
com.google.ads.googleads.v21.services.MutateCustomerRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.CustomerServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.CustomerServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.MutateCustomerRequest.class, com.google.ads.googleads.v21.services.MutateCustomerRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v21.services.MutateCustomerRequest.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;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
validateOnly_ = false;
responseContentType_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.services.CustomerServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateCustomerRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v21.services.MutateCustomerRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateCustomerRequest build() {
com.google.ads.googleads.v21.services.MutateCustomerRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateCustomerRequest buildPartial() {
com.google.ads.googleads.v21.services.MutateCustomerRequest result = new com.google.ads.googleads.v21.services.MutateCustomerRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.services.MutateCustomerRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
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.validateOnly_ = validateOnly_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.responseContentType_ = responseContentType_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v21.services.MutateCustomerRequest) {
return mergeFrom((com.google.ads.googleads.v21.services.MutateCustomerRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.services.MutateCustomerRequest other) {
if (other == com.google.ads.googleads.v21.services.MutateCustomerRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
if (other.responseContentType_ != 0) {
setResponseContentTypeValue(other.getResponseContentTypeValue());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 34: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 40: {
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 40
case 48: {
responseContentType_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 48
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v21.services.CustomerOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.CustomerOperation, com.google.ads.googleads.v21.services.CustomerOperation.Builder, com.google.ads.googleads.v21.services.CustomerOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v21.services.CustomerOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v21.services.CustomerOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v21.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v21.services.CustomerOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v21.services.CustomerOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v21.services.CustomerOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.services.CustomerOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.services.CustomerOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v21.services.CustomerOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the customer
* </pre>
*
* <code>.google.ads.googleads.v21.services.CustomerOperation operation = 4 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.CustomerOperation, com.google.ads.googleads.v21.services.CustomerOperation.Builder, com.google.ads.googleads.v21.services.CustomerOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.CustomerOperation, com.google.ads.googleads.v21.services.CustomerOperation.Builder, com.google.ads.googleads.v21.services.CustomerOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</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, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 5;</code>
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The enum numeric value on the wire for responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentTypeValue(int value) {
responseContentType_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return The responseContentType.
*/
@java.lang.Override
public com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.forNumber(responseContentType_);
return result == null ? com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @param value The responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentType(com.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
responseContentType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 6;</code>
* @return This builder for chaining.
*/
public Builder clearResponseContentType() {
bitField0_ = (bitField0_ & ~0x00000008);
responseContentType_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.services.MutateCustomerRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.MutateCustomerRequest)
private static final com.google.ads.googleads.v21.services.MutateCustomerRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.MutateCustomerRequest();
}
public static com.google.ads.googleads.v21.services.MutateCustomerRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateCustomerRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateCustomerRequest>() {
@java.lang.Override
public MutateCustomerRequest 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<MutateCustomerRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateCustomerRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateCustomerRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,013 | java-cloudsupport/proto-google-cloud-cloudsupport-v2beta/src/main/java/com/google/cloud/support/v2beta/CaseClassification.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/support/v2beta/case.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.support.v2beta;
/**
*
*
* <pre>
* A Case Classification represents the topic that a case is about. It's very
* important to use accurate classifications, because they're
* used to route your cases to specialists who can help you.
*
* A classification always has an ID that is its unique identifier.
* A valid ID is required when creating a case.
* </pre>
*
* Protobuf type {@code google.cloud.support.v2beta.CaseClassification}
*/
public final class CaseClassification extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.support.v2beta.CaseClassification)
CaseClassificationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CaseClassification.newBuilder() to construct.
private CaseClassification(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CaseClassification() {
id_ = "";
displayName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CaseClassification();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.support.v2beta.CaseProto
.internal_static_google_cloud_support_v2beta_CaseClassification_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.support.v2beta.CaseProto
.internal_static_google_cloud_support_v2beta_CaseClassification_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.support.v2beta.CaseClassification.class,
com.google.cloud.support.v2beta.CaseClassification.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object id_ = "";
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @return The id.
*/
@java.lang.Override
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @return The bytes for id.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @return The displayName.
*/
@java.lang.Override
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
}
}
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @return The bytes for displayName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PRODUCT_FIELD_NUMBER = 10;
private com.google.cloud.support.v2beta.Product product_;
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*
* @return Whether the product field is set.
*/
@java.lang.Override
public boolean hasProduct() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*
* @return The product.
*/
@java.lang.Override
public com.google.cloud.support.v2beta.Product getProduct() {
return product_ == null
? com.google.cloud.support.v2beta.Product.getDefaultInstance()
: product_;
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
@java.lang.Override
public com.google.cloud.support.v2beta.ProductOrBuilder getProductOrBuilder() {
return product_ == null
? com.google.cloud.support.v2beta.Product.getDefaultInstance()
: product_;
}
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(id_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, id_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, displayName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(10, getProduct());
}
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(id_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, id_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, displayName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(10, getProduct());
}
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.support.v2beta.CaseClassification)) {
return super.equals(obj);
}
com.google.cloud.support.v2beta.CaseClassification other =
(com.google.cloud.support.v2beta.CaseClassification) obj;
if (!getId().equals(other.getId())) return false;
if (!getDisplayName().equals(other.getDisplayName())) return false;
if (hasProduct() != other.hasProduct()) return false;
if (hasProduct()) {
if (!getProduct().equals(other.getProduct())) 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) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
if (hasProduct()) {
hash = (37 * hash) + PRODUCT_FIELD_NUMBER;
hash = (53 * hash) + getProduct().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.support.v2beta.CaseClassification parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.support.v2beta.CaseClassification 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.support.v2beta.CaseClassification parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.support.v2beta.CaseClassification 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.support.v2beta.CaseClassification parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.support.v2beta.CaseClassification parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.support.v2beta.CaseClassification parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.support.v2beta.CaseClassification 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.support.v2beta.CaseClassification parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.support.v2beta.CaseClassification 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.support.v2beta.CaseClassification parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.support.v2beta.CaseClassification 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.support.v2beta.CaseClassification 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 Case Classification represents the topic that a case is about. It's very
* important to use accurate classifications, because they're
* used to route your cases to specialists who can help you.
*
* A classification always has an ID that is its unique identifier.
* A valid ID is required when creating a case.
* </pre>
*
* Protobuf type {@code google.cloud.support.v2beta.CaseClassification}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.support.v2beta.CaseClassification)
com.google.cloud.support.v2beta.CaseClassificationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.support.v2beta.CaseProto
.internal_static_google_cloud_support_v2beta_CaseClassification_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.support.v2beta.CaseProto
.internal_static_google_cloud_support_v2beta_CaseClassification_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.support.v2beta.CaseClassification.class,
com.google.cloud.support.v2beta.CaseClassification.Builder.class);
}
// Construct using com.google.cloud.support.v2beta.CaseClassification.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getProductFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
id_ = "";
displayName_ = "";
product_ = null;
if (productBuilder_ != null) {
productBuilder_.dispose();
productBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.support.v2beta.CaseProto
.internal_static_google_cloud_support_v2beta_CaseClassification_descriptor;
}
@java.lang.Override
public com.google.cloud.support.v2beta.CaseClassification getDefaultInstanceForType() {
return com.google.cloud.support.v2beta.CaseClassification.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.support.v2beta.CaseClassification build() {
com.google.cloud.support.v2beta.CaseClassification result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.support.v2beta.CaseClassification buildPartial() {
com.google.cloud.support.v2beta.CaseClassification result =
new com.google.cloud.support.v2beta.CaseClassification(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.support.v2beta.CaseClassification result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.id_ = id_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.displayName_ = displayName_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.product_ = productBuilder_ == null ? product_ : productBuilder_.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.support.v2beta.CaseClassification) {
return mergeFrom((com.google.cloud.support.v2beta.CaseClassification) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.support.v2beta.CaseClassification other) {
if (other == com.google.cloud.support.v2beta.CaseClassification.getDefaultInstance())
return this;
if (!other.getId().isEmpty()) {
id_ = other.id_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getDisplayName().isEmpty()) {
displayName_ = other.displayName_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasProduct()) {
mergeProduct(other.getProduct());
}
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 26:
{
id_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 26
case 34:
{
displayName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 34
case 82:
{
input.readMessage(getProductFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 82
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 id_ = "";
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @return The id.
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @return The bytes for id.
*/
public com.google.protobuf.ByteString getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearId() {
id_ = getDefaultInstance().getId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The unique ID for a classification. Must be specified for case creation.
*
* To retrieve valid classification IDs for case creation, use
* `caseClassifications.search`.
*
* Classification IDs returned by `caseClassifications.search` are guaranteed
* to be valid for at least 6 months. If a given classification is
* deactiveated, it will immediately stop being returned. After 6 months,
* `case.create` requests using the classification ID will fail.
* </pre>
*
* <code>string id = 3;</code>
*
* @param value The bytes for id to set.
* @return This builder for chaining.
*/
public Builder setIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @return The displayName.
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @return The bytes for displayName.
*/
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @param value The displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
displayName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearDisplayName() {
displayName_ = getDefaultInstance().getDisplayName();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A display name for the classification.
*
* The display name is not static and can change. To uniquely and consistently
* identify classifications, use the `CaseClassification.id` field.
* </pre>
*
* <code>string display_name = 4;</code>
*
* @param value The bytes for displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
displayName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.support.v2beta.Product product_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.support.v2beta.Product,
com.google.cloud.support.v2beta.Product.Builder,
com.google.cloud.support.v2beta.ProductOrBuilder>
productBuilder_;
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*
* @return Whether the product field is set.
*/
public boolean hasProduct() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*
* @return The product.
*/
public com.google.cloud.support.v2beta.Product getProduct() {
if (productBuilder_ == null) {
return product_ == null
? com.google.cloud.support.v2beta.Product.getDefaultInstance()
: product_;
} else {
return productBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public Builder setProduct(com.google.cloud.support.v2beta.Product value) {
if (productBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
product_ = value;
} else {
productBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public Builder setProduct(com.google.cloud.support.v2beta.Product.Builder builderForValue) {
if (productBuilder_ == null) {
product_ = builderForValue.build();
} else {
productBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public Builder mergeProduct(com.google.cloud.support.v2beta.Product value) {
if (productBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& product_ != null
&& product_ != com.google.cloud.support.v2beta.Product.getDefaultInstance()) {
getProductBuilder().mergeFrom(value);
} else {
product_ = value;
}
} else {
productBuilder_.mergeFrom(value);
}
if (product_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public Builder clearProduct() {
bitField0_ = (bitField0_ & ~0x00000004);
product_ = null;
if (productBuilder_ != null) {
productBuilder_.dispose();
productBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public com.google.cloud.support.v2beta.Product.Builder getProductBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getProductFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
public com.google.cloud.support.v2beta.ProductOrBuilder getProductOrBuilder() {
if (productBuilder_ != null) {
return productBuilder_.getMessageOrBuilder();
} else {
return product_ == null
? com.google.cloud.support.v2beta.Product.getDefaultInstance()
: product_;
}
}
/**
*
*
* <pre>
* The full product the classification corresponds to.
* </pre>
*
* <code>.google.cloud.support.v2beta.Product product = 10;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.support.v2beta.Product,
com.google.cloud.support.v2beta.Product.Builder,
com.google.cloud.support.v2beta.ProductOrBuilder>
getProductFieldBuilder() {
if (productBuilder_ == null) {
productBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.support.v2beta.Product,
com.google.cloud.support.v2beta.Product.Builder,
com.google.cloud.support.v2beta.ProductOrBuilder>(
getProduct(), getParentForChildren(), isClean());
product_ = null;
}
return productBuilder_;
}
@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.support.v2beta.CaseClassification)
}
// @@protoc_insertion_point(class_scope:google.cloud.support.v2beta.CaseClassification)
private static final com.google.cloud.support.v2beta.CaseClassification DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.support.v2beta.CaseClassification();
}
public static com.google.cloud.support.v2beta.CaseClassification getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CaseClassification> PARSER =
new com.google.protobuf.AbstractParser<CaseClassification>() {
@java.lang.Override
public CaseClassification 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<CaseClassification> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CaseClassification> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.support.v2beta.CaseClassification getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,044 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SetLabelsSnapshotRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for Snapshots.SetLabels. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SetLabelsSnapshotRequest}
*/
public final class SetLabelsSnapshotRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SetLabelsSnapshotRequest)
SetLabelsSnapshotRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use SetLabelsSnapshotRequest.newBuilder() to construct.
private SetLabelsSnapshotRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SetLabelsSnapshotRequest() {
project_ = "";
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SetLabelsSnapshotRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetLabelsSnapshotRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetLabelsSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SetLabelsSnapshotRequest.class,
com.google.cloud.compute.v1.SetLabelsSnapshotRequest.Builder.class);
}
private int bitField0_;
public static final int GLOBAL_SET_LABELS_REQUEST_RESOURCE_FIELD_NUMBER = 319917189;
private com.google.cloud.compute.v1.GlobalSetLabelsRequest globalSetLabelsRequestResource_;
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the globalSetLabelsRequestResource field is set.
*/
@java.lang.Override
public boolean hasGlobalSetLabelsRequestResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The globalSetLabelsRequestResource.
*/
@java.lang.Override
public com.google.cloud.compute.v1.GlobalSetLabelsRequest getGlobalSetLabelsRequestResource() {
return globalSetLabelsRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()
: globalSetLabelsRequestResource_;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder
getGlobalSetLabelsRequestResourceOrBuilder() {
return globalSetLabelsRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()
: globalSetLabelsRequestResource_;
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_FIELD_NUMBER = 195806222;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(319917189, getGlobalSetLabelsRequestResource());
}
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(195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
319917189, getGlobalSetLabelsRequestResource());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.SetLabelsSnapshotRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.SetLabelsSnapshotRequest other =
(com.google.cloud.compute.v1.SetLabelsSnapshotRequest) obj;
if (hasGlobalSetLabelsRequestResource() != other.hasGlobalSetLabelsRequestResource())
return false;
if (hasGlobalSetLabelsRequestResource()) {
if (!getGlobalSetLabelsRequestResource().equals(other.getGlobalSetLabelsRequestResource()))
return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getResource().equals(other.getResource())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasGlobalSetLabelsRequestResource()) {
hash = (37 * hash) + GLOBAL_SET_LABELS_REQUEST_RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGlobalSetLabelsRequestResource().hashCode();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.SetLabelsSnapshotRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for Snapshots.SetLabels. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.SetLabelsSnapshotRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SetLabelsSnapshotRequest)
com.google.cloud.compute.v1.SetLabelsSnapshotRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetLabelsSnapshotRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetLabelsSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SetLabelsSnapshotRequest.class,
com.google.cloud.compute.v1.SetLabelsSnapshotRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.SetLabelsSnapshotRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getGlobalSetLabelsRequestResourceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
globalSetLabelsRequestResource_ = null;
if (globalSetLabelsRequestResourceBuilder_ != null) {
globalSetLabelsRequestResourceBuilder_.dispose();
globalSetLabelsRequestResourceBuilder_ = null;
}
project_ = "";
resource_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SetLabelsSnapshotRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetLabelsSnapshotRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.SetLabelsSnapshotRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.SetLabelsSnapshotRequest build() {
com.google.cloud.compute.v1.SetLabelsSnapshotRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetLabelsSnapshotRequest buildPartial() {
com.google.cloud.compute.v1.SetLabelsSnapshotRequest result =
new com.google.cloud.compute.v1.SetLabelsSnapshotRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.SetLabelsSnapshotRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.globalSetLabelsRequestResource_ =
globalSetLabelsRequestResourceBuilder_ == null
? globalSetLabelsRequestResource_
: globalSetLabelsRequestResourceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.resource_ = resource_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.SetLabelsSnapshotRequest) {
return mergeFrom((com.google.cloud.compute.v1.SetLabelsSnapshotRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.SetLabelsSnapshotRequest other) {
if (other == com.google.cloud.compute.v1.SetLabelsSnapshotRequest.getDefaultInstance())
return this;
if (other.hasGlobalSetLabelsRequestResource()) {
mergeGlobalSetLabelsRequestResource(other.getGlobalSetLabelsRequestResource());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
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 1566449778:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1566449778
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -1735629782:
{
input.readMessage(
getGlobalSetLabelsRequestResourceFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case -1735629782
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.compute.v1.GlobalSetLabelsRequest globalSetLabelsRequestResource_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetLabelsRequest,
com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder,
com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder>
globalSetLabelsRequestResourceBuilder_;
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the globalSetLabelsRequestResource field is set.
*/
public boolean hasGlobalSetLabelsRequestResource() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The globalSetLabelsRequestResource.
*/
public com.google.cloud.compute.v1.GlobalSetLabelsRequest getGlobalSetLabelsRequestResource() {
if (globalSetLabelsRequestResourceBuilder_ == null) {
return globalSetLabelsRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()
: globalSetLabelsRequestResource_;
} else {
return globalSetLabelsRequestResourceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGlobalSetLabelsRequestResource(
com.google.cloud.compute.v1.GlobalSetLabelsRequest value) {
if (globalSetLabelsRequestResourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
globalSetLabelsRequestResource_ = value;
} else {
globalSetLabelsRequestResourceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGlobalSetLabelsRequestResource(
com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder builderForValue) {
if (globalSetLabelsRequestResourceBuilder_ == null) {
globalSetLabelsRequestResource_ = builderForValue.build();
} else {
globalSetLabelsRequestResourceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeGlobalSetLabelsRequestResource(
com.google.cloud.compute.v1.GlobalSetLabelsRequest value) {
if (globalSetLabelsRequestResourceBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& globalSetLabelsRequestResource_ != null
&& globalSetLabelsRequestResource_
!= com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()) {
getGlobalSetLabelsRequestResourceBuilder().mergeFrom(value);
} else {
globalSetLabelsRequestResource_ = value;
}
} else {
globalSetLabelsRequestResourceBuilder_.mergeFrom(value);
}
if (globalSetLabelsRequestResource_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearGlobalSetLabelsRequestResource() {
bitField0_ = (bitField0_ & ~0x00000001);
globalSetLabelsRequestResource_ = null;
if (globalSetLabelsRequestResourceBuilder_ != null) {
globalSetLabelsRequestResourceBuilder_.dispose();
globalSetLabelsRequestResourceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder
getGlobalSetLabelsRequestResourceBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getGlobalSetLabelsRequestResourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder
getGlobalSetLabelsRequestResourceOrBuilder() {
if (globalSetLabelsRequestResourceBuilder_ != null) {
return globalSetLabelsRequestResourceBuilder_.getMessageOrBuilder();
} else {
return globalSetLabelsRequestResource_ == null
? com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()
: globalSetLabelsRequestResource_;
}
}
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.GlobalSetLabelsRequest global_set_labels_request_resource = 319917189 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetLabelsRequest,
com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder,
com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder>
getGlobalSetLabelsRequestResourceFieldBuilder() {
if (globalSetLabelsRequestResourceBuilder_ == null) {
globalSetLabelsRequestResourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.GlobalSetLabelsRequest,
com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder,
com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder>(
getGlobalSetLabelsRequestResource(), getParentForChildren(), isClean());
globalSetLabelsRequestResource_ = null;
}
return globalSetLabelsRequestResourceBuilder_;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.SetLabelsSnapshotRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SetLabelsSnapshotRequest)
private static final com.google.cloud.compute.v1.SetLabelsSnapshotRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.SetLabelsSnapshotRequest();
}
public static com.google.cloud.compute.v1.SetLabelsSnapshotRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SetLabelsSnapshotRequest> PARSER =
new com.google.protobuf.AbstractParser<SetLabelsSnapshotRequest>() {
@java.lang.Override
public SetLabelsSnapshotRequest 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<SetLabelsSnapshotRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SetLabelsSnapshotRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.SetLabelsSnapshotRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,050 | java-data-fusion/proto-google-cloud-data-fusion-v1/src/main/java/com/google/cloud/datafusion/v1/ListAvailableVersionsResponse.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/datafusion/v1/datafusion.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datafusion.v1;
/**
*
*
* <pre>
* Response message for the list available versions request.
* </pre>
*
* Protobuf type {@code google.cloud.datafusion.v1.ListAvailableVersionsResponse}
*/
public final class ListAvailableVersionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datafusion.v1.ListAvailableVersionsResponse)
ListAvailableVersionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAvailableVersionsResponse.newBuilder() to construct.
private ListAvailableVersionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAvailableVersionsResponse() {
availableVersions_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAvailableVersionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datafusion.v1.Datafusion
.internal_static_google_cloud_datafusion_v1_ListAvailableVersionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datafusion.v1.Datafusion
.internal_static_google_cloud_datafusion_v1_ListAvailableVersionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.class,
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.Builder.class);
}
public static final int AVAILABLE_VERSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datafusion.v1.Version> availableVersions_;
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datafusion.v1.Version> getAvailableVersionsList() {
return availableVersions_;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datafusion.v1.VersionOrBuilder>
getAvailableVersionsOrBuilderList() {
return availableVersions_;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
@java.lang.Override
public int getAvailableVersionsCount() {
return availableVersions_.size();
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datafusion.v1.Version getAvailableVersions(int index) {
return availableVersions_.get(index);
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datafusion.v1.VersionOrBuilder getAvailableVersionsOrBuilder(int index) {
return availableVersions_.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 < availableVersions_.size(); i++) {
output.writeMessage(1, availableVersions_.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 < availableVersions_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(1, availableVersions_.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.datafusion.v1.ListAvailableVersionsResponse)) {
return super.equals(obj);
}
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse other =
(com.google.cloud.datafusion.v1.ListAvailableVersionsResponse) obj;
if (!getAvailableVersionsList().equals(other.getAvailableVersionsList())) 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 (getAvailableVersionsCount() > 0) {
hash = (37 * hash) + AVAILABLE_VERSIONS_FIELD_NUMBER;
hash = (53 * hash) + getAvailableVersionsList().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.datafusion.v1.ListAvailableVersionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse 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 list available versions request.
* </pre>
*
* Protobuf type {@code google.cloud.datafusion.v1.ListAvailableVersionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datafusion.v1.ListAvailableVersionsResponse)
com.google.cloud.datafusion.v1.ListAvailableVersionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datafusion.v1.Datafusion
.internal_static_google_cloud_datafusion_v1_ListAvailableVersionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datafusion.v1.Datafusion
.internal_static_google_cloud_datafusion_v1_ListAvailableVersionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.class,
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.Builder.class);
}
// Construct using com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (availableVersionsBuilder_ == null) {
availableVersions_ = java.util.Collections.emptyList();
} else {
availableVersions_ = null;
availableVersionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datafusion.v1.Datafusion
.internal_static_google_cloud_datafusion_v1_ListAvailableVersionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.datafusion.v1.ListAvailableVersionsResponse
getDefaultInstanceForType() {
return com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datafusion.v1.ListAvailableVersionsResponse build() {
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datafusion.v1.ListAvailableVersionsResponse buildPartial() {
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse result =
new com.google.cloud.datafusion.v1.ListAvailableVersionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse result) {
if (availableVersionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
availableVersions_ = java.util.Collections.unmodifiableList(availableVersions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.availableVersions_ = availableVersions_;
} else {
result.availableVersions_ = availableVersionsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.datafusion.v1.ListAvailableVersionsResponse 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.datafusion.v1.ListAvailableVersionsResponse) {
return mergeFrom((com.google.cloud.datafusion.v1.ListAvailableVersionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datafusion.v1.ListAvailableVersionsResponse other) {
if (other
== com.google.cloud.datafusion.v1.ListAvailableVersionsResponse.getDefaultInstance())
return this;
if (availableVersionsBuilder_ == null) {
if (!other.availableVersions_.isEmpty()) {
if (availableVersions_.isEmpty()) {
availableVersions_ = other.availableVersions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAvailableVersionsIsMutable();
availableVersions_.addAll(other.availableVersions_);
}
onChanged();
}
} else {
if (!other.availableVersions_.isEmpty()) {
if (availableVersionsBuilder_.isEmpty()) {
availableVersionsBuilder_.dispose();
availableVersionsBuilder_ = null;
availableVersions_ = other.availableVersions_;
bitField0_ = (bitField0_ & ~0x00000001);
availableVersionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAvailableVersionsFieldBuilder()
: null;
} else {
availableVersionsBuilder_.addAllMessages(other.availableVersions_);
}
}
}
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.datafusion.v1.Version m =
input.readMessage(
com.google.cloud.datafusion.v1.Version.parser(), extensionRegistry);
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
availableVersions_.add(m);
} else {
availableVersionsBuilder_.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.datafusion.v1.Version> availableVersions_ =
java.util.Collections.emptyList();
private void ensureAvailableVersionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
availableVersions_ =
new java.util.ArrayList<com.google.cloud.datafusion.v1.Version>(availableVersions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datafusion.v1.Version,
com.google.cloud.datafusion.v1.Version.Builder,
com.google.cloud.datafusion.v1.VersionOrBuilder>
availableVersionsBuilder_;
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public java.util.List<com.google.cloud.datafusion.v1.Version> getAvailableVersionsList() {
if (availableVersionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(availableVersions_);
} else {
return availableVersionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public int getAvailableVersionsCount() {
if (availableVersionsBuilder_ == null) {
return availableVersions_.size();
} else {
return availableVersionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public com.google.cloud.datafusion.v1.Version getAvailableVersions(int index) {
if (availableVersionsBuilder_ == null) {
return availableVersions_.get(index);
} else {
return availableVersionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder setAvailableVersions(int index, com.google.cloud.datafusion.v1.Version value) {
if (availableVersionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAvailableVersionsIsMutable();
availableVersions_.set(index, value);
onChanged();
} else {
availableVersionsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder setAvailableVersions(
int index, com.google.cloud.datafusion.v1.Version.Builder builderForValue) {
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
availableVersions_.set(index, builderForValue.build());
onChanged();
} else {
availableVersionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder addAvailableVersions(com.google.cloud.datafusion.v1.Version value) {
if (availableVersionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAvailableVersionsIsMutable();
availableVersions_.add(value);
onChanged();
} else {
availableVersionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder addAvailableVersions(int index, com.google.cloud.datafusion.v1.Version value) {
if (availableVersionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAvailableVersionsIsMutable();
availableVersions_.add(index, value);
onChanged();
} else {
availableVersionsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder addAvailableVersions(
com.google.cloud.datafusion.v1.Version.Builder builderForValue) {
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
availableVersions_.add(builderForValue.build());
onChanged();
} else {
availableVersionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder addAvailableVersions(
int index, com.google.cloud.datafusion.v1.Version.Builder builderForValue) {
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
availableVersions_.add(index, builderForValue.build());
onChanged();
} else {
availableVersionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder addAllAvailableVersions(
java.lang.Iterable<? extends com.google.cloud.datafusion.v1.Version> values) {
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, availableVersions_);
onChanged();
} else {
availableVersionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder clearAvailableVersions() {
if (availableVersionsBuilder_ == null) {
availableVersions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
availableVersionsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public Builder removeAvailableVersions(int index) {
if (availableVersionsBuilder_ == null) {
ensureAvailableVersionsIsMutable();
availableVersions_.remove(index);
onChanged();
} else {
availableVersionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public com.google.cloud.datafusion.v1.Version.Builder getAvailableVersionsBuilder(int index) {
return getAvailableVersionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public com.google.cloud.datafusion.v1.VersionOrBuilder getAvailableVersionsOrBuilder(
int index) {
if (availableVersionsBuilder_ == null) {
return availableVersions_.get(index);
} else {
return availableVersionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public java.util.List<? extends com.google.cloud.datafusion.v1.VersionOrBuilder>
getAvailableVersionsOrBuilderList() {
if (availableVersionsBuilder_ != null) {
return availableVersionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(availableVersions_);
}
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public com.google.cloud.datafusion.v1.Version.Builder addAvailableVersionsBuilder() {
return getAvailableVersionsFieldBuilder()
.addBuilder(com.google.cloud.datafusion.v1.Version.getDefaultInstance());
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public com.google.cloud.datafusion.v1.Version.Builder addAvailableVersionsBuilder(int index) {
return getAvailableVersionsFieldBuilder()
.addBuilder(index, com.google.cloud.datafusion.v1.Version.getDefaultInstance());
}
/**
*
*
* <pre>
* Represents a list of versions that are supported.
* </pre>
*
* <code>repeated .google.cloud.datafusion.v1.Version available_versions = 1;</code>
*/
public java.util.List<com.google.cloud.datafusion.v1.Version.Builder>
getAvailableVersionsBuilderList() {
return getAvailableVersionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datafusion.v1.Version,
com.google.cloud.datafusion.v1.Version.Builder,
com.google.cloud.datafusion.v1.VersionOrBuilder>
getAvailableVersionsFieldBuilder() {
if (availableVersionsBuilder_ == null) {
availableVersionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datafusion.v1.Version,
com.google.cloud.datafusion.v1.Version.Builder,
com.google.cloud.datafusion.v1.VersionOrBuilder>(
availableVersions_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
availableVersions_ = null;
}
return availableVersionsBuilder_;
}
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.datafusion.v1.ListAvailableVersionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.datafusion.v1.ListAvailableVersionsResponse)
private static final com.google.cloud.datafusion.v1.ListAvailableVersionsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datafusion.v1.ListAvailableVersionsResponse();
}
public static com.google.cloud.datafusion.v1.ListAvailableVersionsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAvailableVersionsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAvailableVersionsResponse>() {
@java.lang.Override
public ListAvailableVersionsResponse 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<ListAvailableVersionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAvailableVersionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datafusion.v1.ListAvailableVersionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/jackrabbit | 38,152 | jackrabbit-jcr-tests/src/main/java/org/apache/jackrabbit/test/api/SetValueConstraintViolationExceptionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.test.api;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeIterator;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.PropertyDefinition;
import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.jackrabbit.test.NotExecutableException;
import org.apache.jackrabbit.test.api.nodetype.NodeTypeUtil;
/**
* <code>SetValueConstraintViolationExceptionTest</code> tests if setValue()
* throws a ConstraintViolationException either immediately (by setValue()) or
* on save, if the change would violate a value constraint.
*
*/
public class SetValueConstraintViolationExceptionTest extends AbstractJCRTest {
/**
* Tests if setValue(InputStream value) and setValue(Value value) where
* value is a BinaryValue throw a ConstraintViolationException if the change
* would violate a value constraint
*/
public void testBinaryProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.BINARY, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No binary property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied1 = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
Value valueNotSatisfied2 = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied1 == null || valueNotSatisfied2 == null) {
throw new NotExecutableException("No binary property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), valueSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(InputStream value)
InputStream in = valueNotSatisfied1.getStream();
try {
prop.setValue(in);
node.save();
fail("setValue(InputStream value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
} finally {
try { in.close(); } catch (IOException ignore) {}
}
// test of signature setValue(Value value)
try {
prop.setValue(valueNotSatisfied2);
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(boolean value) and setValue(Value value) where value is
* a BooleanValue throw a ConstraintViolationException if the change would
* violate a value constraint
*/
public void testBooleanProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.BOOLEAN, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No boolean property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No boolean property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), valueSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(boolean value)
try {
prop.setValue(valueNotSatisfied.getBoolean());
node.save();
fail("setValue(boolean value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
// test of signature setValue(Value value)
try {
prop.setValue(valueNotSatisfied);
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Calendar value) and setValue(Value value) where value
* is a DateValue throw a ConstraintViolationException if the change would
* violate a value constraint
*/
public void testDateProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.DATE, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No date property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No date property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), valueSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(Calendar value)
try {
prop.setValue(valueNotSatisfied.getDate());
node.save();
fail("setValue(Date value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
// test of signature setValue(Value value)
try {
prop.setValue(valueNotSatisfied);
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Double value) and setValue(Value value) where value is
* a DoubleValue throw a ConstraintViolationException if the change would
* violate a value constraint
*/
public void testDoubleProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.DOUBLE, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No double property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No double property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), valueSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(double value)
try {
prop.setValue(valueNotSatisfied.getDouble());
node.save();
fail("setValue(double value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
// test of signature setValue(Value value)
try {
prop.setValue(valueNotSatisfied);
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Long value) and setValue(Value value) where value is a
* LongValue throw a ConstraintViolationException if the change would
* violate a value constraint
*/
public void testLongProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.LONG, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No long property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No long property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), valueSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(long value)
try {
prop.setValue(valueNotSatisfied.getLong());
node.save();
fail("setValue(long value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
// test of signature setValue(Value value)
try {
prop.setValue(valueNotSatisfied);
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Node value) and setValue(Value value) where value is a
* ReferenceValue throw a ConstraintViolationException if the change would
* violate a value constraint
*/
public void testReferenceProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.REFERENCE, false, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No reference property def with " +
"testable value constraints has been found");
}
String valueConstraints[] = propDef.getValueConstraints();
if (valueConstraints == null || valueConstraints.length == 0) {
throw new NotExecutableException("No reference property def with "
+ "testable value constraints has been found");
}
List<String> constraints = Arrays.asList(valueConstraints);
String nodeTypeSatisfied = constraints.get(0);
String nodeTypeNotSatisfied = null;
NodeTypeManager manager = superuser.getWorkspace().getNodeTypeManager();
NodeTypeIterator types = manager.getAllNodeTypes();
// find a NodeType which is not satisfying the constraints
while (types.hasNext()) {
NodeType type = types.nextNodeType();
String name = type.getName();
if (constraints.contains(name) || ntFrozenNode.equals(name)) {
continue;
}
if (type.getChildNodeDefinitions() != null
&& type.getChildNodeDefinitions().length > 0) {
continue;
}
nodeTypeNotSatisfied = name;
break;
}
if (nodeTypeNotSatisfied == null) {
throw new NotExecutableException("No reference property def with " +
"testable value constraints has been found");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
Node nodeSatisfied;
Node nodeNotSatisfied;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
// create a referenceable node satisfying the constraint
nodeSatisfied = testRootNode.addNode(nodeName3, nodeTypeSatisfied);
ensureMixinType(nodeSatisfied, mixReferenceable);
// create a referenceable node not satisfying the constraint
nodeNotSatisfied = testRootNode.addNode(nodeName4, nodeTypeNotSatisfied);
ensureMixinType(nodeNotSatisfied, mixReferenceable);
// some implementations may require a save after addMixin()
testRootNode.getSession().save();
prop = node.setProperty(propDef.getName(), nodeSatisfied);
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(Node value)
try {
prop.setValue(nodeNotSatisfied);
node.save();
fail("setValue(Node value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
// test of signature setValue(Value value)
try {
prop.setValue(superuser.getValueFactory().createValue(nodeNotSatisfied));
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type BinaryValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleBinaryProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.BINARY, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple binary property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No multiple binary property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
try {
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value[] values) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type BooleanValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleBooleanProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.BOOLEAN, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple boolean property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No multiple boolean property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
try {
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value[] values) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type DateValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleDateProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.DATE, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple date property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No multiple date property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
try {
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value[] values) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type DoubleValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleDoubleProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.DOUBLE, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple double property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No multiple double property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(Value value)
try {
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value[] values) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type LongValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleLongProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.LONG, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple long property def with " +
"testable value constraints has been found");
}
// find a Value that does not satisfy the ValueConstraints of propDef
Value valueNotSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, false);
if (valueNotSatisfied == null) {
throw new NotExecutableException("No multiple long property def with " +
"testable value constraints has been found");
}
// find a Value that does satisfy the ValueConstraints of propDef
Value valueSatisfied = NodeTypeUtil.getValueAccordingToValueConstraints(superuser, propDef, true);
if (valueSatisfied == null) {
throw new NotExecutableException("The value constraints do not allow any value.");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(Value value)
try {
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value value) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
/**
* Tests if setValue(Value[] values) where values are of type ReferenceValue
* throw a ConstraintViolationException if the change would violate a value
* constraint
*/
public void testMultipleReferenceProperty()
throws NotExecutableException, RepositoryException {
// locate a PropertyDefinition with ValueConstraints
PropertyDefinition propDef =
NodeTypeUtil.locatePropertyDef(superuser, PropertyType.REFERENCE, true, false, true, false);
if (propDef == null) {
throw new NotExecutableException("No multiple reference property def with " +
"testable value constraints has been found");
}
String valueConstraints[] = propDef.getValueConstraints();
if (valueConstraints == null || valueConstraints.length == 0) {
throw new NotExecutableException("No reference property def with "
+ "testable value constraints has been found");
}
List<String> constraints = Arrays.asList(valueConstraints);
String nodeTypeSatisfied = constraints.get(0);
String nodeTypeNotSatisfied = null;
NodeTypeManager manager = superuser.getWorkspace().getNodeTypeManager();
NodeTypeIterator types = manager.getAllNodeTypes();
// find a NodeType which is not satisfying the constraints
while (types.hasNext()) {
NodeType type = types.nextNodeType();
String name = type.getName();
if (constraints.contains(name) || ntFrozenNode.equals(name)) {
continue;
}
if (type.getChildNodeDefinitions() != null
&& type.getChildNodeDefinitions().length > 0) {
continue;
}
nodeTypeNotSatisfied = name;
break;
}
if (nodeTypeNotSatisfied == null) {
throw new NotExecutableException("No reference property def with " +
"testable value constraints has been found");
}
// create a sub node of testRootNode of type propDef.getDeclaringNodeType()
// and add a property with constraints to this node
Node node;
Property prop;
Node nodeSatisfied;
Node nodeNotSatisfied;
try {
String nodeType = propDef.getDeclaringNodeType().getName();
node = testRootNode.addNode(nodeName2, nodeType);
// create a referenceable node satisfying the constraint
nodeSatisfied = testRootNode.addNode(nodeName3, nodeTypeSatisfied);
ensureMixinType(nodeSatisfied, mixReferenceable);
// create a referenceable node not satisfying the constraint
nodeNotSatisfied = testRootNode.addNode(nodeName4, nodeTypeNotSatisfied);
ensureMixinType(nodeNotSatisfied, mixReferenceable);
// some implementations may require a save after addMixin()
testRootNode.getSession().save();
Value valueSatisfied = superuser.getValueFactory().createValue(nodeSatisfied);
prop = node.setProperty(propDef.getName(), new Value[]{valueSatisfied});
testRootNode.getSession().save();
} catch (ConstraintViolationException e) {
// implementation specific constraints do not allow to set up test environment
throw new NotExecutableException("Not able to create required test items.");
}
// test of signature setValue(Value value)
try {
Value valueNotSatisfied = superuser.getValueFactory().createValue(nodeNotSatisfied);
prop.setValue(new Value[]{valueNotSatisfied});
node.save();
fail("setValue(Value[] values) must throw a ConstraintViolationException " +
"if the change would violate a node type constraint " +
"either immediately or on save");
} catch (ConstraintViolationException e) {
// success
}
}
}
|
apache/flink | 38,150 | flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.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.api.common.typeutils.base;
import org.apache.flink.FlinkVersion;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerConditions;
import org.apache.flink.api.common.typeutils.TypeSerializerSchemaCompatibility;
import org.apache.flink.api.common.typeutils.TypeSerializerUpgradeTestBase;
import org.apache.flink.types.BooleanValue;
import org.apache.flink.types.ByteValue;
import org.apache.flink.types.CharValue;
import org.apache.flink.types.DoubleValue;
import org.apache.flink.types.FloatValue;
import org.apache.flink.types.IntValue;
import org.apache.flink.types.LongValue;
import org.apache.flink.types.NullValue;
import org.apache.flink.types.ShortValue;
import org.apache.flink.types.StringValue;
import org.assertj.core.api.Condition;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
/** Test specifications for {@link BasicTypeSerializerUpgradeTest}. */
public class BasicTypeSerializerUpgradeTestSpecifications {
// ----------------------------------------------------------------------------------------------
// Specification for "big-dec-serializer"
// ----------------------------------------------------------------------------------------------
/** BigDecSerializerSetup. */
public static final class BigDecSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<BigDecimal> {
@Override
public TypeSerializer<BigDecimal> createPriorSerializer() {
return BigDecSerializer.INSTANCE;
}
@Override
public BigDecimal createTestData() {
return new BigDecimal("123456789012345678901234567890123456.789");
}
}
/** BigDecSerializerVerifier. */
public static final class BigDecSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<BigDecimal> {
@Override
public TypeSerializer<BigDecimal> createUpgradedSerializer() {
return BigDecSerializer.INSTANCE;
}
@Override
public Condition<BigDecimal> testDataCondition() {
return new Condition<>(
value ->
value.equals(
new BigDecimal("123456789012345678901234567890123456.789")),
"value is 123456789012345678901234567890123456.789");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<BigDecimal>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "big-int-serializer"
// ----------------------------------------------------------------------------------------------
/** BigIntSerializerSetup. */
public static final class BigIntSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<BigInteger> {
@Override
public TypeSerializer<BigInteger> createPriorSerializer() {
return BigIntSerializer.INSTANCE;
}
@Override
public BigInteger createTestData() {
return new BigInteger("123456789012345678901234567890123456");
}
}
/** BigIntSerializerVerifier. */
public static final class BigIntSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<BigInteger> {
@Override
public TypeSerializer<BigInteger> createUpgradedSerializer() {
return BigIntSerializer.INSTANCE;
}
@Override
public Condition<BigInteger> testDataCondition() {
return new Condition<>(
value -> value.equals(new BigInteger("123456789012345678901234567890123456")),
"value is 123456789012345678901234567890123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<BigInteger>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "BooleanSerializer"
// ----------------------------------------------------------------------------------------------
/** BooleanSerializerSetup. */
public static final class BooleanSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Boolean> {
@Override
public TypeSerializer<Boolean> createPriorSerializer() {
return BooleanSerializer.INSTANCE;
}
@Override
public Boolean createTestData() {
return Boolean.TRUE;
}
}
/** BooleanSerializerVerifier. */
public static final class BooleanSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Boolean> {
@Override
public TypeSerializer<Boolean> createUpgradedSerializer() {
return BooleanSerializer.INSTANCE;
}
@Override
public Condition<Boolean> testDataCondition() {
return new Condition<>(Boolean.TRUE::equals, "value is true");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Boolean>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "boolean-value-serializer"
// ----------------------------------------------------------------------------------------------
/** BooleanValueSerializerSetup. */
public static final class BooleanValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<BooleanValue> {
@Override
public TypeSerializer<BooleanValue> createPriorSerializer() {
return BooleanValueSerializer.INSTANCE;
}
@Override
public BooleanValue createTestData() {
return BooleanValue.TRUE;
}
}
/** BooleanValueSerializerVerifier. */
public static final class BooleanValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<BooleanValue> {
@Override
public TypeSerializer<BooleanValue> createUpgradedSerializer() {
return BooleanValueSerializer.INSTANCE;
}
@Override
public Condition<BooleanValue> testDataCondition() {
return new Condition<>(BooleanValue.TRUE::equals, "value is true");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<BooleanValue>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "byte-serializer"
// ----------------------------------------------------------------------------------------------
/** ByteSerializerSetup. */
public static final class ByteSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Byte> {
@Override
public TypeSerializer<Byte> createPriorSerializer() {
return ByteSerializer.INSTANCE;
}
@Override
public Byte createTestData() {
return Byte.valueOf("42");
}
}
/** ByteSerializerVerifier. */
public static final class ByteSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Byte> {
@Override
public TypeSerializer<Byte> createUpgradedSerializer() {
return ByteSerializer.INSTANCE;
}
@Override
public Condition<Byte> testDataCondition() {
return new Condition<>(value -> value.equals(Byte.valueOf("42")), "value is 42");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Byte>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "byte-value-serializer"
// ----------------------------------------------------------------------------------------------
/** ByteValueSerializerSetup. */
public static final class ByteValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<ByteValue> {
@Override
public TypeSerializer<ByteValue> createPriorSerializer() {
return ByteValueSerializer.INSTANCE;
}
@Override
public ByteValue createTestData() {
return new ByteValue((byte) 42);
}
}
/** ByteValueSerializerVerifier. */
public static final class ByteValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<ByteValue> {
@Override
public TypeSerializer<ByteValue> createUpgradedSerializer() {
return ByteValueSerializer.INSTANCE;
}
@Override
public Condition<ByteValue> testDataCondition() {
return new Condition<>(new ByteValue((byte) 42)::equals, "value is 42");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<ByteValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "char-serializer"
// ----------------------------------------------------------------------------------------------
/** CharSerializerSetup. */
public static final class CharSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Character> {
@Override
public TypeSerializer<Character> createPriorSerializer() {
return CharSerializer.INSTANCE;
}
@Override
public Character createTestData() {
return Character.MAX_VALUE;
}
}
/** CharSerializerVerifier. */
public static final class CharSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Character> {
@Override
public TypeSerializer<Character> createUpgradedSerializer() {
return CharSerializer.INSTANCE;
}
@Override
public Condition<Character> testDataCondition() {
return new Condition<>(
value -> value.equals(Character.MAX_VALUE), "value is Character.MAX_VALUE");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Character>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "char-value-serializer"
// ----------------------------------------------------------------------------------------------
/** CharValueSerializerSetup. */
public static final class CharValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<CharValue> {
@Override
public TypeSerializer<CharValue> createPriorSerializer() {
return CharValueSerializer.INSTANCE;
}
@Override
public CharValue createTestData() {
return new CharValue((char) 42);
}
}
/** CharValueSerializerVerifier. */
public static final class CharValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<CharValue> {
@Override
public TypeSerializer<CharValue> createUpgradedSerializer() {
return CharValueSerializer.INSTANCE;
}
@Override
public Condition<CharValue> testDataCondition() {
return new Condition<>(new CharValue((char) 42)::equals, "value is 42");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<CharValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "date-serializer"
// ----------------------------------------------------------------------------------------------
/** DateSerializerSetup. */
public static final class DateSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Date> {
@Override
public TypeSerializer<Date> createPriorSerializer() {
return DateSerializer.INSTANCE;
}
@Override
public Date createTestData() {
return new Date(1580382960L);
}
}
/** DateSerializerVerifier. */
public static final class DateSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Date> {
@Override
public TypeSerializer<Date> createUpgradedSerializer() {
return DateSerializer.INSTANCE;
}
@Override
public Condition<Date> testDataCondition() {
return new Condition<>(new Date(1580382960L)::equals, "value is 1580382960L");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Date>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "double-serializer"
// ----------------------------------------------------------------------------------------------
/** DoubleSerializerSetup. */
public static final class DoubleSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Double> {
@Override
public TypeSerializer<Double> createPriorSerializer() {
return DoubleSerializer.INSTANCE;
}
@Override
public Double createTestData() {
return new Double("12345.6789");
}
}
/** DoubleSerializerVerifier. */
public static final class DoubleSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Double> {
@Override
public TypeSerializer<Double> createUpgradedSerializer() {
return DoubleSerializer.INSTANCE;
}
@Override
public Condition<Double> testDataCondition() {
return new Condition<>(new Double("12345.6789")::equals, "value is 12345.6789");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Double>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "double-value-serializer"
// ----------------------------------------------------------------------------------------------
/** DoubleValueSerializerSetup. */
public static final class DoubleValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<DoubleValue> {
@Override
public TypeSerializer<DoubleValue> createPriorSerializer() {
return DoubleValueSerializer.INSTANCE;
}
@Override
public DoubleValue createTestData() {
return new DoubleValue(12345.6789);
}
}
/** DoubleValueSerializerVerifier. */
public static final class DoubleValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<DoubleValue> {
@Override
public TypeSerializer<DoubleValue> createUpgradedSerializer() {
return DoubleValueSerializer.INSTANCE;
}
@Override
public Condition<DoubleValue> testDataCondition() {
return new Condition<>(new DoubleValue(12345.6789)::equals, "value is 12345.6789");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<DoubleValue>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "float-serializer"
// ----------------------------------------------------------------------------------------------
/** FloatSerializerSetup. */
public static final class FloatSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Float> {
@Override
public TypeSerializer<Float> createPriorSerializer() {
return FloatSerializer.INSTANCE;
}
@Override
public Float createTestData() {
return new Float("123.456");
}
}
/** FloatSerializerVerifier. */
public static final class FloatSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Float> {
@Override
public TypeSerializer<Float> createUpgradedSerializer() {
return FloatSerializer.INSTANCE;
}
@Override
public Condition<Float> testDataCondition() {
return new Condition<>(new Float("123.456")::equals, "value is 123.456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Float>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "float-value-serializer"
// ----------------------------------------------------------------------------------------------
/** FloatValueSerializerSetup. */
public static final class FloatValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<FloatValue> {
@Override
public TypeSerializer<FloatValue> createPriorSerializer() {
return FloatValueSerializer.INSTANCE;
}
@Override
public FloatValue createTestData() {
return new FloatValue(123.456f);
}
}
/** FloatValueSerializerVerifier. */
public static final class FloatValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<FloatValue> {
@Override
public TypeSerializer<FloatValue> createUpgradedSerializer() {
return FloatValueSerializer.INSTANCE;
}
@Override
public Condition<FloatValue> testDataCondition() {
return new Condition<>(new FloatValue(123.456f)::equals, "value is 123.456f");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<FloatValue>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "int-serializer"
// ----------------------------------------------------------------------------------------------
/** IntSerializerSetup. */
public static final class IntSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Integer> {
@Override
public TypeSerializer<Integer> createPriorSerializer() {
return IntSerializer.INSTANCE;
}
@Override
public Integer createTestData() {
return 123456;
}
}
/** IntSerializerVerifier. */
public static final class IntSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Integer> {
@Override
public TypeSerializer<Integer> createUpgradedSerializer() {
return IntSerializer.INSTANCE;
}
@Override
public Condition<Integer> testDataCondition() {
return new Condition<>(value -> value.equals(123456), "value is 123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Integer>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "int-value-serializer"
// ----------------------------------------------------------------------------------------------
/** IntValueSerializerSetup. */
public static final class IntValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<IntValue> {
@Override
public TypeSerializer<IntValue> createPriorSerializer() {
return IntValueSerializer.INSTANCE;
}
@Override
public IntValue createTestData() {
return new IntValue(123456);
}
}
/** IntValueSerializerVerifier. */
public static final class IntValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<IntValue> {
@Override
public TypeSerializer<IntValue> createUpgradedSerializer() {
return IntValueSerializer.INSTANCE;
}
@Override
public Condition<IntValue> testDataCondition() {
return new Condition<>(new IntValue(123456)::equals, "value is 123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<IntValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "long-serializer"
// ----------------------------------------------------------------------------------------------
/** LongSerializerSetup. */
public static final class LongSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Long> {
@Override
public TypeSerializer<Long> createPriorSerializer() {
return LongSerializer.INSTANCE;
}
@Override
public Long createTestData() {
return 1234567890L;
}
}
/** LongSerializerVerifier. */
public static final class LongSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Long> {
@Override
public TypeSerializer<Long> createUpgradedSerializer() {
return LongSerializer.INSTANCE;
}
@Override
public Condition<Long> testDataCondition() {
return new Condition<>(value -> value.equals(1234567890L), "value is 1234567890L");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Long>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "long-value-serializer"
// ----------------------------------------------------------------------------------------------
/** LongValueSerializerSetup. */
public static final class LongValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<LongValue> {
@Override
public TypeSerializer<LongValue> createPriorSerializer() {
return LongValueSerializer.INSTANCE;
}
@Override
public LongValue createTestData() {
return new LongValue(1234567890);
}
}
/** LongValueSerializerVerifier. */
public static final class LongValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<LongValue> {
@Override
public TypeSerializer<LongValue> createUpgradedSerializer() {
return LongValueSerializer.INSTANCE;
}
@Override
public Condition<LongValue> testDataCondition() {
return new Condition<>(new LongValue(1234567890)::equals, "value is 1234567890");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<LongValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "null-value-serializer"
// ----------------------------------------------------------------------------------------------
/** NullValueSerializerSetup. */
public static final class NullValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<NullValue> {
@Override
public TypeSerializer<NullValue> createPriorSerializer() {
return NullValueSerializer.INSTANCE;
}
@Override
public NullValue createTestData() {
return NullValue.getInstance();
}
}
/** NullValueSerializerVerifier. */
public static final class NullValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<NullValue> {
@Override
public TypeSerializer<NullValue> createUpgradedSerializer() {
return NullValueSerializer.INSTANCE;
}
@Override
public Condition<NullValue> testDataCondition() {
return new Condition<>(
NullValue.getInstance()::equals, "value is NullValue.getInstance()");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<NullValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "short-serializer"
// ----------------------------------------------------------------------------------------------
/** ShortSerializerSetup. */
public static final class ShortSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Short> {
@Override
public TypeSerializer<Short> createPriorSerializer() {
return ShortSerializer.INSTANCE;
}
@Override
public Short createTestData() {
return 123;
}
}
/** ShortSerializerVerifier. */
public static final class ShortSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Short> {
@Override
public TypeSerializer<Short> createUpgradedSerializer() {
return ShortSerializer.INSTANCE;
}
@Override
public Condition<Short> testDataCondition() {
return new Condition<>(value -> value == 123, "value is 123");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Short>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "short-value-serializer"
// ----------------------------------------------------------------------------------------------
/** ShortValueSerializerSetup. */
public static final class ShortValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<ShortValue> {
@Override
public TypeSerializer<ShortValue> createPriorSerializer() {
return ShortValueSerializer.INSTANCE;
}
@Override
public ShortValue createTestData() {
return new ShortValue((short) 123);
}
}
/** ShortValueSerializerVerifier. */
public static final class ShortValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<ShortValue> {
@Override
public TypeSerializer<ShortValue> createUpgradedSerializer() {
return ShortValueSerializer.INSTANCE;
}
@Override
public Condition<ShortValue> testDataCondition() {
return new Condition<>(new ShortValue((short) 123)::equals, "value is 123");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<ShortValue>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "sql-date-serializer"
// ----------------------------------------------------------------------------------------------
/** SqlDateSerializerSetup. */
public static final class SqlDateSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<java.sql.Date> {
@Override
public TypeSerializer<java.sql.Date> createPriorSerializer() {
return SqlDateSerializer.INSTANCE;
}
@Override
public java.sql.Date createTestData() {
return new java.sql.Date(1580382960L);
}
}
/** SqlDateSerializerVerifier. */
public static final class SqlDateSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<java.sql.Date> {
@Override
public TypeSerializer<java.sql.Date> createUpgradedSerializer() {
return SqlDateSerializer.INSTANCE;
}
@Override
public Condition<java.sql.Date> testDataCondition() {
return new Condition<>(
value -> value.equals(new java.sql.Date(1580382960L)), "value is 1580382960L");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<java.sql.Date>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "sql-time-serializer"
// ----------------------------------------------------------------------------------------------
/** SqlTimeSerializerSetup. */
public static final class SqlTimeSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Time> {
@Override
public TypeSerializer<Time> createPriorSerializer() {
return SqlTimeSerializer.INSTANCE;
}
@Override
public Time createTestData() {
return new Time(1580382960L);
}
}
/** SqlTimeSerializerVerifier. */
public static final class SqlTimeSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Time> {
@Override
public TypeSerializer<Time> createUpgradedSerializer() {
return SqlTimeSerializer.INSTANCE;
}
@Override
public Condition<Time> testDataCondition() {
return new Condition<>(
value -> value.equals(new Time(1580382960L)), "value is 1580382960L");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Time>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "sql-timestamp-serializer"
// ----------------------------------------------------------------------------------------------
/** SqlTimestampSerializerSetup. */
public static final class SqlTimestampSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Timestamp> {
@Override
public TypeSerializer<Timestamp> createPriorSerializer() {
return SqlTimestampSerializer.INSTANCE;
}
@Override
public Timestamp createTestData() {
return new Timestamp(1580382960L);
}
}
/** SqlTimestampSerializerVerifier. */
public static final class SqlTimestampSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<Timestamp> {
@Override
public TypeSerializer<Timestamp> createUpgradedSerializer() {
return SqlTimestampSerializer.INSTANCE;
}
@Override
public Condition<Timestamp> testDataCondition() {
return new Condition<>(
value -> value.equals(new Timestamp(1580382960L)), "value is 1580382960L");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<Timestamp>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "string-serializer"
// ----------------------------------------------------------------------------------------------
/** StringSerializerSetup. */
public static final class StringSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<String> {
@Override
public TypeSerializer<String> createPriorSerializer() {
return StringSerializer.INSTANCE;
}
@Override
public String createTestData() {
return "123456789012345678901234567890123456";
}
}
/** StringSerializerVerifier. */
public static final class StringSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<String> {
@Override
public TypeSerializer<String> createUpgradedSerializer() {
return StringSerializer.INSTANCE;
}
@Override
public Condition<String> testDataCondition() {
return new Condition<>(
value -> value.equals("123456789012345678901234567890123456"),
"value is 123456789012345678901234567890123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<String>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "string-value-serializer"
// ----------------------------------------------------------------------------------------------
/** StringValueSerializerSetup. */
public static final class StringValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<StringValue> {
@Override
public TypeSerializer<StringValue> createPriorSerializer() {
return StringValueSerializer.INSTANCE;
}
@Override
public StringValue createTestData() {
return new StringValue("123456789012345678901234567890123456");
}
}
/** StringValueSerializerVerifier. */
public static final class StringValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<StringValue> {
@Override
public TypeSerializer<StringValue> createUpgradedSerializer() {
return StringValueSerializer.INSTANCE;
}
@Override
public Condition<StringValue> testDataCondition() {
return new Condition<>(
new StringValue("123456789012345678901234567890123456")::equals,
"value is 123456789012345678901234567890123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<StringValue>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
}
|
apache/hadoop | 38,204 | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/balancer/TestBalancerLongRunningTasks.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.balancer;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.DFSUtilClient;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.NameNodeProxies;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicy;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyWithUpgradeDomain;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementStatus;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.LazyPersistTestCase;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.metrics2.MetricsSystem;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.apache.hadoop.fs.StorageType.DEFAULT;
import static org.apache.hadoop.fs.StorageType.RAM_DISK;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BALANCER_MAX_SIZE_TO_MOVE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_BLOCK_PINNING_ENABLED;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_LAZY_WRITER_INTERVAL_SEC;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_MAX_LOCKED_MEMORY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC;
import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Some long running Balancer tasks.
*/
public class TestBalancerLongRunningTasks {
private static final Logger LOG =
LoggerFactory.getLogger(TestBalancerLongRunningTasks.class);
static {
GenericTestUtils.setLogLevel(Balancer.LOG, Level.TRACE);
GenericTestUtils.setLogLevel(Dispatcher.LOG, Level.DEBUG);
}
private final static long CAPACITY = 5000L;
private final static String RACK0 = "/rack0";
private final static String RACK1 = "/rack1";
private final static String RACK2 = "/rack2";
private final static String FILE_NAME = "/tmp.txt";
private final static Path FILE_PATH = new Path(FILE_NAME);
private MiniDFSCluster cluster;
@AfterEach
public void shutdown() throws Exception {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
private ClientProtocol client;
static final int DEFAULT_BLOCK_SIZE = 100;
static final int DEFAULT_RAM_DISK_BLOCK_SIZE = 5 * 1024 * 1024;
static {
initTestSetup();
}
public static void initTestSetup() {
// do not create id file since it occupies the disk space
NameNodeConnector.setWrite2IdFile(false);
}
static void initConf(Configuration conf) {
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, DEFAULT_BLOCK_SIZE);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 500);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1L);
SimulatedFSDataset.setFactory(conf);
conf.setLong(DFSConfigKeys.DFS_BALANCER_MOVEDWINWIDTH_KEY, 2000L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1L);
conf.setInt(DFSConfigKeys.DFS_BALANCER_MAX_NO_MOVE_INTERVAL_KEY, 5 * 1000);
}
static void initConfWithRamDisk(Configuration conf,
long ramDiskCapacity) {
conf.setLong(DFS_BLOCK_SIZE_KEY, DEFAULT_RAM_DISK_BLOCK_SIZE);
conf.setLong(DFS_DATANODE_MAX_LOCKED_MEMORY_KEY, ramDiskCapacity);
conf.setInt(DFS_NAMENODE_LAZY_PERSIST_FILE_SCRUB_INTERVAL_SEC, 3);
conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1);
conf.setInt(DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 500);
conf.setInt(DFS_DATANODE_LAZY_WRITER_INTERVAL_SEC, 1);
conf.setInt(DFSConfigKeys.DFS_BALANCER_MAX_NO_MOVE_INTERVAL_KEY, 5 * 1000);
LazyPersistTestCase.initCacheManipulator();
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1L);
}
/**
* Test special case. Two replicas belong to same block should not in same
* node.
* We have 2 nodes.
* We have a block in (DN0,SSD) and (DN1,DISK).
* Replica in (DN0,SSD) should not be moved to (DN1,SSD).
* Otherwise DN1 has 2 replicas.
*/
@Test
@Timeout(value = 100)
public void testTwoReplicaShouldNotInSameDN() throws Exception {
final Configuration conf = new HdfsConfiguration();
int blockSize = 5 * 1024 * 1024;
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1L);
int numOfDatanodes = 2;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(2)
.racks(new String[]{"/default/rack0", "/default/rack0"})
.storagesPerDatanode(2)
.storageTypes(new StorageType[][]{
{StorageType.SSD, StorageType.DISK},
{StorageType.SSD, StorageType.DISK}})
.storageCapacities(new long[][]{
{100 * blockSize, 20 * blockSize},
{20 * blockSize, 100 * blockSize}})
.build();
cluster.waitActive();
//set "/bar" directory with ONE_SSD storage policy.
DistributedFileSystem fs = cluster.getFileSystem();
Path barDir = new Path("/bar");
fs.mkdir(barDir, new FsPermission((short) 777));
fs.setStoragePolicy(barDir, HdfsConstants.ONESSD_STORAGE_POLICY_NAME);
// Insert 30 blocks. So (DN0,SSD) and (DN1,DISK) are about half full,
// and (DN0,SSD) and (DN1,DISK) are about 15% full.
long fileLen = 30 * blockSize;
// fooFile has ONE_SSD policy. So
// (DN0,SSD) and (DN1,DISK) have 2 replicas belong to same block.
// (DN0,DISK) and (DN1,SSD) have 2 replicas belong to same block.
Path fooFile = new Path(barDir, "foo");
TestBalancer.createFile(cluster, fooFile, fileLen, (short) numOfDatanodes,
0);
// update space info
cluster.triggerHeartbeats();
BalancerParameters p = BalancerParameters.DEFAULT;
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
final int r = Balancer.run(namenodes, p, conf);
// Replica in (DN0,SSD) was not moved to (DN1,SSD), because (DN1,DISK)
// already has one. Otherwise DN1 will have 2 replicas.
// For same reason, no replicas were moved.
assertEquals(ExitStatus.NO_MOVE_PROGRESS.getExitCode(), r);
}
/*
* Test Balancer with Ram_Disk configured
* One DN has two files on RAM_DISK, other DN has no files on RAM_DISK.
* Then verify that the balancer does not migrate files on RAM_DISK across DN.
*/
@Test
@Timeout(value = 300)
public void testBalancerWithRamDisk() throws Exception {
final int seed = 0xFADED;
final short replicationFactor = 1;
Configuration conf = new Configuration();
final int defaultRamDiskCapacity = 10;
final long ramDiskStorageLimit =
((long) defaultRamDiskCapacity * DEFAULT_RAM_DISK_BLOCK_SIZE) +
(DEFAULT_RAM_DISK_BLOCK_SIZE - 1);
final long diskStorageLimit =
((long) defaultRamDiskCapacity * DEFAULT_RAM_DISK_BLOCK_SIZE) +
(DEFAULT_RAM_DISK_BLOCK_SIZE - 1);
initConfWithRamDisk(conf, ramDiskStorageLimit);
cluster = new MiniDFSCluster
.Builder(conf)
.numDataNodes(1)
.storageCapacities(new long[]{ramDiskStorageLimit, diskStorageLimit})
.storageTypes(new StorageType[]{RAM_DISK, DEFAULT})
.build();
cluster.waitActive();
// Create few files on RAM_DISK
final String methodName = GenericTestUtils.getMethodName();
final Path path1 = new Path("/" + methodName + ".01.dat");
final Path path2 = new Path("/" + methodName + ".02.dat");
DistributedFileSystem fs = cluster.getFileSystem();
DFSClient dfsClient = fs.getClient();
DFSTestUtil.createFile(fs, path1, true,
DEFAULT_RAM_DISK_BLOCK_SIZE, 4 * DEFAULT_RAM_DISK_BLOCK_SIZE,
DEFAULT_RAM_DISK_BLOCK_SIZE, replicationFactor, seed, true);
DFSTestUtil.createFile(fs, path2, true,
DEFAULT_RAM_DISK_BLOCK_SIZE, 1 * DEFAULT_RAM_DISK_BLOCK_SIZE,
DEFAULT_RAM_DISK_BLOCK_SIZE, replicationFactor, seed, true);
// Sleep for a short time to allow the lazy writer thread to do its job
Thread.sleep(6 * 1000);
// Add another fresh DN with the same type/capacity without files on
// RAM_DISK
StorageType[][] storageTypes = new StorageType[][]{{RAM_DISK, DEFAULT}};
long[][] storageCapacities = new long[][]{{ramDiskStorageLimit,
diskStorageLimit}};
cluster.startDataNodes(conf, replicationFactor, storageTypes, true, null,
null, null, storageCapacities, null, false, false, false, null, null, null);
cluster.triggerHeartbeats();
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
// Run Balancer
final BalancerParameters p = BalancerParameters.DEFAULT;
final int r = Balancer.run(namenodes, p, conf);
// Validate no RAM_DISK block should be moved
assertEquals(ExitStatus.NO_MOVE_PROGRESS.getExitCode(), r);
// Verify files are still on RAM_DISK
DFSTestUtil.verifyFileReplicasOnStorageType(fs, dfsClient, path1, RAM_DISK);
DFSTestUtil.verifyFileReplicasOnStorageType(fs, dfsClient, path2, RAM_DISK);
}
/**
* Balancer should not move blocks with size < minBlockSize.
*/
@Test
@Timeout(value = 60)
public void testMinBlockSizeAndSourceNodes() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
final short replication = 3;
final long[] lengths = {10, 10, 10, 10};
final long[] capacities = new long[replication];
final long totalUsed = capacities.length * TestBalancer.sum(lengths);
Arrays.fill(capacities, 1000);
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(capacities.length)
.simulatedCapacities(capacities)
.build();
final DistributedFileSystem dfs = cluster.getFileSystem();
cluster.waitActive();
client = NameNodeProxies.createProxy(conf, dfs.getUri(),
ClientProtocol.class).getProxy();
// fill up the cluster to be 80% full
for (int i = 0; i < lengths.length; i++) {
final long size = lengths[i];
final Path p = new Path("/file" + i + "_size" + size);
try (OutputStream out = dfs.create(p)) {
for (int j = 0; j < size; j++) {
out.write(j);
}
}
}
// start up an empty node with the same capacity
cluster.startDataNodes(conf, capacities.length, true, null, null, capacities);
LOG.info("capacities = " + Arrays.toString(capacities));
LOG.info("totalUsedSpace= " + totalUsed);
LOG.info("lengths = " + Arrays.toString(lengths) + ", #=" + lengths.length);
TestBalancer.waitForHeartBeat(totalUsed,
2 * capacities[0] * capacities.length, client, cluster);
final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
{ // run Balancer with min-block-size=50
final BalancerParameters p = Balancer.Cli.parse(new String[]{
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1"
});
assertEquals(p.getBalancingPolicy(), BalancingPolicy.Node.INSTANCE);
assertEquals(p.getThreshold(), 1.0, 0.001);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 50);
final int r = Balancer.run(namenodes, p, conf);
assertEquals(ExitStatus.NO_MOVE_PROGRESS.getExitCode(), r);
}
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1);
{ // run Balancer with empty nodes as source nodes
final Set<String> sourceNodes = new HashSet<>();
final List<DataNode> datanodes = cluster.getDataNodes();
for (int i = capacities.length; i < datanodes.size(); i++) {
sourceNodes.add(datanodes.get(i).getDisplayName());
}
final BalancerParameters p = Balancer.Cli.parse(new String[]{
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1",
"-source", StringUtils.join(sourceNodes, ',')
});
assertEquals(p.getBalancingPolicy(), BalancingPolicy.Node.INSTANCE);
assertEquals(p.getThreshold(), 1.0, 0.001);
assertEquals(p.getSourceNodes(), sourceNodes);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 50);
final int r = Balancer.run(namenodes, p, conf);
assertEquals(ExitStatus.NO_MOVE_BLOCK.getExitCode(), r);
}
{ // run Balancer with a filled node as a source node
final Set<String> sourceNodes = new HashSet<>();
final List<DataNode> datanodes = cluster.getDataNodes();
sourceNodes.add(datanodes.get(0).getDisplayName());
final BalancerParameters p = Balancer.Cli.parse(new String[]{
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1",
"-source", StringUtils.join(sourceNodes, ',')
});
assertEquals(p.getBalancingPolicy(), BalancingPolicy.Node.INSTANCE);
assertEquals(p.getThreshold(), 1.0, 0.001);
assertEquals(p.getSourceNodes(), sourceNodes);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1);
final int r = Balancer.run(namenodes, p, conf);
assertEquals(ExitStatus.NO_MOVE_BLOCK.getExitCode(), r);
}
{ // run Balancer with all filled node as source nodes
final Set<String> sourceNodes = new HashSet<>();
final List<DataNode> datanodes = cluster.getDataNodes();
for (int i = 0; i < capacities.length; i++) {
sourceNodes.add(datanodes.get(i).getDisplayName());
}
final BalancerParameters p = Balancer.Cli.parse(new String[]{
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1",
"-source", StringUtils.join(sourceNodes, ',')
});
assertEquals(p.getBalancingPolicy(), BalancingPolicy.Node.INSTANCE);
assertEquals(p.getThreshold(), 1.0, 0.001);
assertEquals(p.getSourceNodes(), sourceNodes);
conf.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, 1);
final int r = Balancer.run(namenodes, p, conf);
assertEquals(ExitStatus.SUCCESS.getExitCode(), r);
}
}
/**
* Verify balancer won't violate upgrade domain block placement policy.
*
* @throws Exception
*/
@Test
@Timeout(value = 100)
public void testUpgradeDomainPolicyAfterBalance() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
conf.setClass(DFSConfigKeys.DFS_BLOCK_REPLICATOR_CLASSNAME_KEY,
BlockPlacementPolicyWithUpgradeDomain.class,
BlockPlacementPolicy.class);
long[] capacities = new long[]{CAPACITY, CAPACITY, CAPACITY};
String[] hosts = {"host0", "host1", "host2"};
String[] racks = {RACK0, RACK1, RACK1};
String[] uds = {"ud0", "ud1", "ud2"};
runBalancerAndVerifyBlockPlacmentPolicy(conf, capacities, hosts, racks,
uds, CAPACITY, "host3", RACK2, "ud2");
}
/**
* Verify balancer won't violate the default block placement policy.
*
* @throws Exception
*/
@Test
@Timeout(value = 100)
public void testRackPolicyAfterBalance() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
long[] capacities = new long[]{CAPACITY, CAPACITY};
String[] hosts = {"host0", "host1"};
String[] racks = {RACK0, RACK1};
runBalancerAndVerifyBlockPlacmentPolicy(conf, capacities, hosts, racks,
null, CAPACITY, "host2", RACK1, null);
}
private void runBalancerAndVerifyBlockPlacmentPolicy(Configuration conf,
long[] capacities, String[] hosts, String[] racks, String[] UDs,
long newCapacity, String newHost, String newRack, String newUD)
throws Exception {
int numOfDatanodes = capacities.length;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(capacities.length)
.hosts(hosts).racks(racks).simulatedCapacities(capacities).build();
DatanodeManager dm = cluster.getNamesystem().getBlockManager().
getDatanodeManager();
if (UDs != null) {
for (int i = 0; i < UDs.length; i++) {
DatanodeID datanodeId = cluster.getDataNodes().get(i).getDatanodeId();
dm.getDatanode(datanodeId).setUpgradeDomain(UDs[i]);
}
}
try {
cluster.waitActive();
client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
// fill up the cluster to be 80% full
long totalCapacity = TestBalancer.sum(capacities);
long totalUsedSpace = totalCapacity * 8 / 10;
final long fileSize = totalUsedSpace / numOfDatanodes;
DFSTestUtil.createFile(cluster.getFileSystem(0), FILE_PATH, false, 1024,
fileSize, DEFAULT_BLOCK_SIZE, (short) numOfDatanodes, 0, false);
// start up an empty node with the same capacity on the same rack as the
// pinned host.
cluster.startDataNodes(conf, 1, true, null, new String[]{newRack},
new String[]{newHost}, new long[]{newCapacity});
if (newUD != null) {
DatanodeID newId = cluster.getDataNodes().get(
numOfDatanodes).getDatanodeId();
dm.getDatanode(newId).setUpgradeDomain(newUD);
}
totalCapacity += newCapacity;
// run balancer and validate results
TestBalancer.waitForHeartBeat(totalUsedSpace,
totalCapacity, client, cluster);
// start rebalancing
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
Balancer.run(namenodes, BalancerParameters.DEFAULT, conf);
BlockPlacementPolicy placementPolicy =
cluster.getNamesystem().getBlockManager().getBlockPlacementPolicy();
List<LocatedBlock> locatedBlocks = client.
getBlockLocations(FILE_NAME, 0, fileSize).getLocatedBlocks();
for (LocatedBlock locatedBlock : locatedBlocks) {
BlockPlacementStatus status = placementPolicy.verifyBlockPlacement(
locatedBlock.getLocations(), numOfDatanodes);
assertTrue(status.isPlacementPolicySatisfied());
}
} finally {
cluster.shutdown();
}
}
/**
* Make sure that balancer can't move pinned blocks.
* If specified favoredNodes when create file, blocks will be pinned use
* sticky bit.
*
* @throws Exception
*/
@Test
@Timeout(value = 100)
public void testBalancerWithPinnedBlocks() throws Exception {
// This test assumes stick-bit based block pin mechanism available only
// in Linux/Unix. It can be unblocked on Windows when HDFS-7759 is ready to
// provide a different mechanism for Windows.
assumeNotWindows();
final Configuration conf = new HdfsConfiguration();
initConf(conf);
conf.setBoolean(DFS_DATANODE_BLOCK_PINNING_ENABLED, true);
long[] capacities = new long[]{CAPACITY, CAPACITY};
String[] hosts = {"host0", "host1"};
String[] racks = {RACK0, RACK1};
int numOfDatanodes = capacities.length;
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(capacities.length)
.hosts(hosts).racks(racks).simulatedCapacities(capacities).build();
cluster.waitActive();
client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
// fill up the cluster to be 80% full
long totalCapacity = TestBalancer.sum(capacities);
long totalUsedSpace = totalCapacity * 8 / 10;
InetSocketAddress[] favoredNodes = new InetSocketAddress[numOfDatanodes];
for (int i = 0; i < favoredNodes.length; i++) {
// DFSClient will attempt reverse lookup. In case it resolves
// "127.0.0.1" to "localhost", we manually specify the hostname.
int port = cluster.getDataNodes().get(i).getXferAddress().getPort();
favoredNodes[i] = new InetSocketAddress(hosts[i], port);
}
DFSTestUtil.createFile(cluster.getFileSystem(0), FILE_PATH, false, 1024,
totalUsedSpace / numOfDatanodes, DEFAULT_BLOCK_SIZE,
(short) numOfDatanodes, 0, false, favoredNodes);
// start up an empty node with the same capacity
cluster.startDataNodes(conf, 1, true, null, new String[]{RACK2},
new long[]{CAPACITY});
totalCapacity += CAPACITY;
// run balancer and validate results
TestBalancer.waitForHeartBeat(totalUsedSpace, totalCapacity, client,
cluster);
// start rebalancing
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
int r = Balancer.run(namenodes, BalancerParameters.DEFAULT, conf);
assertEquals(ExitStatus.NO_MOVE_PROGRESS.getExitCode(), r);
}
@Test
@Timeout(value = 60)
public void testBalancerWithSortTopNodes() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
conf.setInt(DFS_HEARTBEAT_INTERVAL_KEY, 30000);
final long capacity = 1000L;
final int diffBetweenNodes = 50;
// Set up the datanodes with two groups:
// 5 over-utilized nodes with 80%, 85%, 90%, 95%, 100% usage
// 2 under-utilizaed nodes with 0%, 5% usage
// With sortTopNodes option, 100% and 95% used ones will be chosen.
final int numOfOverUtilizedDn = 5;
final int numOfUnderUtilizedDn = 2;
final int totalNumOfDn = numOfOverUtilizedDn + numOfUnderUtilizedDn;
final long[] capacityArray = new long[totalNumOfDn];
Arrays.fill(capacityArray, capacity);
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalNumOfDn)
.simulatedCapacities(capacityArray)
.build();
cluster.setDataNodesDead();
List<DataNode> dataNodes = cluster.getDataNodes();
// Create top used nodes
for (int i = 0; i < numOfOverUtilizedDn; i++) {
// Bring one node alive
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(i));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(i));
// Create nodes with: 80%, 85%, 90%, 95%, 100%.
int capacityForThisDatanode = (int) capacity
- diffBetweenNodes * (numOfOverUtilizedDn - i - 1);
TestBalancer.createFile(cluster, new Path("test_big" + i),
capacityForThisDatanode, (short) 1, 0);
cluster.setDataNodesDead();
}
// Create under utilized nodes
for (int i = numOfUnderUtilizedDn - 1; i >= 0; i--) {
int index = i + numOfOverUtilizedDn;
// Bring one node alive
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(index));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(index));
// Create nodes with: 5%, 0%
int capacityForThisDatanode = diffBetweenNodes * i;
TestBalancer.createFile(cluster,
new Path("test_small" + i),
capacityForThisDatanode, (short) 1, 0);
cluster.setDataNodesDead();
}
// Bring all nodes alive
cluster.triggerHeartbeats();
cluster.triggerBlockReports();
cluster.waitFirstBRCompleted(0, 6000);
final BalancerParameters p = Balancer.Cli.parse(new String[]{
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1",
"-sortTopNodes"
});
client = NameNodeProxies.createProxy(conf,
cluster.getFileSystem(0).getUri(),
ClientProtocol.class).getProxy();
// Set max-size-to-move to small number
// so only top two nodes will be chosen in one iteration.
conf.setLong(DFS_BALANCER_MAX_SIZE_TO_MOVE_KEY, 99L);
final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
List<NameNodeConnector> connectors = NameNodeConnector
.newNameNodeConnectors(namenodes,
Balancer.class.getSimpleName(), Balancer.BALANCER_ID_PATH, conf,
BalancerParameters.DEFAULT.getMaxIdleIteration());
final Balancer b = new Balancer(connectors.get(0), p, conf);
Balancer.Result balancerResult = b.runOneIteration();
cluster.triggerDeletionReports();
cluster.triggerBlockReports();
cluster.triggerHeartbeats();
DatanodeInfo[] datanodeReport = client
.getDatanodeReport(HdfsConstants.DatanodeReportType.ALL);
long maxUsage = 0;
for (int i = 0; i < totalNumOfDn; i++) {
maxUsage = Math.max(maxUsage, datanodeReport[i].getDfsUsed());
}
// The 95% usage DN will have 9 blocks of 100B and 1 block of 50B - all for the same file.
// The HDFS balancer will choose a block to move from this node randomly. More likely it will
// be 100B block. Since 100B is greater than DFS_BALANCER_MAX_SIZE_TO_MOVE_KEY which is 99L,
// it will stop here. Total bytes moved from this 95% DN will be 1 block of size 100B.
// However, chances are the first block selected to be moved from this 95% DN is the 50B block.
// After this block is moved, the total moved size so far would be 50B which is smaller than
// DFS_BALANCER_MAX_SIZE_TO_MOVE_KEY (99L), hence it will try to move another block.
// The second block will always be of size 100B. So total bytes moved from this 95% DN will be
// 2 blocks of size (100B + 50B) 150B.
// Hence, overall total blocks moved by HDFS balancer would be either of these 2 options:
// a) 2 blocks of total size (100B + 100B)
// b) 3 blocks of total size (50B + 100B + 100B)
assertTrue((balancerResult.getBytesAlreadyMoved() == 200
&& balancerResult.getBlocksMoved() == 2)
|| (balancerResult.getBytesAlreadyMoved() == 250
&& balancerResult.getBlocksMoved() == 3),
"BalancerResult is not as expected. " + balancerResult);
// 100% and 95% used nodes will be balanced, so top used will be 900
assertEquals(900, maxUsage);
}
@Test
@Timeout(value = 60)
public void testBalancerWithLimitOverUtilizedNum() throws Exception {
final Configuration conf = new HdfsConfiguration();
// Init the config (block size to 100)
initConf(conf);
conf.setInt(DFS_HEARTBEAT_INTERVAL_KEY, 30000);
final long totalCapacity = 1000L;
final int diffBetweenNodes = 50;
// Set up the nodes with two groups:
// 5 over-utilized nodes with 80%, 85%, 90%, 95%, 100% usage
// 2 under-utilized nodes with 0%, 5% usage
// With sortTopNodes and limitOverUtilizedNum option, 100% used ones will be chosen
final int numOfOverUtilizedDn = 5;
final int numOfUnderUtilizedDn = 2;
final int totalNumOfDn = numOfOverUtilizedDn + numOfUnderUtilizedDn;
final long[] capacityArray = new long[totalNumOfDn];
Arrays.fill(capacityArray, totalCapacity);
try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalNumOfDn)
.simulatedCapacities(capacityArray)
.build()) {
cluster.setDataNodesDead();
List<DataNode> dataNodes = cluster.getDataNodes();
// Create top used nodes
for (int i = 0; i < numOfOverUtilizedDn; i++) {
// Bring one node alive
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(i));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(i));
// Create nodes with: 80%, 85%, 90%, 95%, 100%
int nodeCapacity = (int) totalCapacity - diffBetweenNodes * (numOfOverUtilizedDn - i - 1);
TestBalancer.createFile(cluster, new Path("test_big" + i), nodeCapacity, (short) 1, 0);
cluster.setDataNodesDead();
}
// Create under utilized nodes
for (int i = numOfUnderUtilizedDn - 1; i >= 0; i--) {
int index = i + numOfOverUtilizedDn;
// Bring one node alive
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(index));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(index));
// Create nodes with: 5%, 0%
int nodeCapacity = diffBetweenNodes * i;
TestBalancer.createFile(cluster, new Path("test_small" + i), nodeCapacity, (short) 1, 0);
cluster.setDataNodesDead();
}
// Bring all nodes alive
cluster.triggerHeartbeats();
cluster.triggerBlockReports();
cluster.waitFirstBRCompleted(0, 6000);
final BalancerParameters balancerParameters = Balancer.Cli.parse(new String[] {
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "1",
"-sortTopNodes",
"-limitOverUtilizedNum", "1"
});
client = NameNodeProxies.createProxy(conf, cluster.getFileSystem(0)
.getUri(), ClientProtocol.class)
.getProxy();
// Set max-size-to-move to small number
// so only top two nodes will be chosen in one iteration
conf.setLong(DFS_BALANCER_MAX_SIZE_TO_MOVE_KEY, 99L);
final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
List<NameNodeConnector> connectors =
NameNodeConnector.newNameNodeConnectors(namenodes, Balancer.class.getSimpleName(),
Balancer.BALANCER_ID_PATH, conf, BalancerParameters.DEFAULT.getMaxIdleIteration());
final Balancer balancer = new Balancer(connectors.get(0), balancerParameters, conf);
Balancer.Result balancerResult = balancer.runOneIteration();
cluster.triggerDeletionReports();
cluster.triggerBlockReports();
cluster.triggerHeartbeats();
DatanodeInfo[] datanodeReport =
client.getDatanodeReport(HdfsConstants.DatanodeReportType.ALL);
long maxUsage = 0;
for (int i = 0; i < totalNumOfDn; i++) {
maxUsage = Math.max(maxUsage, datanodeReport[i].getDfsUsed());
}
// The maxUsage value is 950, only 100% of the nodes will be balanced
assertEquals(950, maxUsage);
assertTrue(
(balancerResult.getBytesAlreadyMoved() == 100 && balancerResult.getBlocksMoved() == 1),
"BalancerResult is not as expected. " + balancerResult);
}
}
@Test
@Timeout(value = 60)
public void testBalancerMetricsDuplicate() throws Exception {
final Configuration conf = new HdfsConfiguration();
// Init the config (block size to 100)
initConf(conf);
final long totalCapacity = 1000L;
final int numOfOverUtilizedDn = 1;
final int numOfUnderUtilizedDn = 2;
final int totalNumOfDn = numOfOverUtilizedDn + numOfUnderUtilizedDn;
final long[] capacityArray = new long[totalNumOfDn];
Arrays.fill(capacityArray, totalCapacity);
try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(totalNumOfDn)
.simulatedCapacities(capacityArray)
.build()) {
cluster.setDataNodesDead();
List<DataNode> dataNodes = cluster.getDataNodes();
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(0));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(0));
// Create nodes with: 100%
TestBalancer.createFile(cluster, new Path("test_big" + 0), 1000, (short) 1, 0);
cluster.setDataNodesDead();
// Two UnderUtilized in the cluster, execute at least twice: b.runOneIteration()
for (int i = 1; i <= numOfUnderUtilizedDn; i++) {
DataNodeTestUtils.triggerHeartbeat(dataNodes.get(i));
DataNodeTestUtils.triggerBlockReport(dataNodes.get(i));
// Create nodes with: 0%
TestBalancer.createFile(cluster, new Path("test_small" + i), 0, (short) 1, 0);
cluster.setDataNodesDead();
}
cluster.triggerDeletionReports();
cluster.triggerBlockReports();
cluster.triggerHeartbeats();
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
Collection<String> nsIds = DFSUtilClient.getNameServiceIds(conf);
assertEquals(1, namenodes.size());
// Throw an error when we double-initialize BalancerMetrics
DefaultMetricsSystem.setMiniClusterMode(false);
MetricsSystem instance = DefaultMetricsSystem.instance();
// Avoid the impact of cluster metric, remove cluster JvmMetrics
instance.unregisterSource("JvmMetrics");
final BalancerParameters balancerParameters = Balancer.Cli.parse(new String[] {
"-policy", BalancingPolicy.Node.INSTANCE.getName(),
"-threshold", "10",
});
int r = Balancer.run(namenodes, nsIds, balancerParameters, conf);
assertEquals(ExitStatus.SUCCESS.getExitCode(), r);
DefaultMetricsSystem.setMiniClusterMode(true);
}
}
@Test
@Timeout(value = 100)
public void testMaxIterationTime() throws Exception {
final Configuration conf = new HdfsConfiguration();
initConf(conf);
int blockSize = 10 * 1024 * 1024; // 10MB block size
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize);
conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, blockSize);
// limit the worker thread count of Balancer to have only 1 queue per DN
conf.setInt(DFSConfigKeys.DFS_BALANCER_MOVERTHREADS_KEY, 1);
// limit the bandwidth to 4MB per sec to emulate slow block moves
conf.setLong(DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY,
4 * 1024 * 1024);
// set client socket timeout to have an IN_PROGRESS notification back from
// the DataNode about the copy in every second.
conf.setLong(HdfsClientConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY, 2000L);
// set max iteration time to 500 ms to timeout before moving any block
conf.setLong(DFSConfigKeys.DFS_BALANCER_MAX_ITERATION_TIME_KEY, 500L);
// setup the cluster
final long capacity = 10L * blockSize;
final long[] dnCapacities = new long[]{capacity, capacity};
final short rep = 1;
final long seed = 0xFAFAFA;
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0)
.build();
try {
cluster.getConfiguration(0).setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, 1);
cluster.startDataNodes(conf, 1, true, null, null, dnCapacities);
cluster.waitClusterUp();
cluster.waitActive();
final Path path = new Path("/testMaxIterationTime.dat");
DistributedFileSystem fs = cluster.getFileSystem();
// fill the DN to 40%
DFSTestUtil.createFile(fs, path, 4L * blockSize, rep, seed);
// start a new DN
cluster.startDataNodes(conf, 1, true, null, null, dnCapacities);
cluster.triggerHeartbeats();
// setup Balancer and run one iteration
List<NameNodeConnector> connectors = Collections.emptyList();
try {
BalancerParameters bParams = BalancerParameters.DEFAULT;
// set maxIdleIterations to 1 for NO_MOVE_PROGRESS to be
// reported when there is no block move
connectors = NameNodeConnector.newNameNodeConnectors(
DFSUtil.getInternalNsRpcUris(conf), Balancer.class.getSimpleName(),
Balancer.BALANCER_ID_PATH, conf, 1);
for (NameNodeConnector nnc : connectors) {
LOG.info("NNC to work on: " + nnc);
Balancer b = new Balancer(nnc, bParams, conf);
Balancer.Result r = b.runOneIteration();
// Since no block can be moved in 500 milli-seconds (i.e.,
// 4MB/s * 0.5s = 2MB < 10MB), NO_MOVE_PROGRESS will be reported.
// When a block move is not canceled in 500 ms properly
// (highly unlikely) and then a block is moved unexpectedly,
// IN_PROGRESS will be reported. This is highly unlikely unexpected
// case. See HDFS-15989.
assertEquals(ExitStatus.NO_MOVE_PROGRESS, r.getExitStatus(),
"We expect ExitStatus.NO_MOVE_PROGRESS to be reported.");
assertEquals(0, r.getBlocksMoved());
}
} finally {
for (NameNodeConnector nnc : connectors) {
IOUtils.cleanupWithLogger(null, nnc);
}
}
} finally {
cluster.shutdown(true, true);
}
}
}
|
googleapis/google-cloud-java | 38,049 | java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/GeneratorSuggestion.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/generator.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* Suggestion generated using a Generator.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.GeneratorSuggestion}
*/
public final class GeneratorSuggestion extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.GeneratorSuggestion)
GeneratorSuggestionOrBuilder {
private static final long serialVersionUID = 0L;
// Use GeneratorSuggestion.newBuilder() to construct.
private GeneratorSuggestion(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GeneratorSuggestion() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GeneratorSuggestion();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.GeneratorProto
.internal_static_google_cloud_dialogflow_v2_GeneratorSuggestion_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.GeneratorProto
.internal_static_google_cloud_dialogflow_v2_GeneratorSuggestion_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.GeneratorSuggestion.class,
com.google.cloud.dialogflow.v2.GeneratorSuggestion.Builder.class);
}
private int suggestionCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object suggestion_;
public enum SuggestionCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
FREE_FORM_SUGGESTION(1),
SUMMARY_SUGGESTION(2),
SUGGESTION_NOT_SET(0);
private final int value;
private SuggestionCase(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 SuggestionCase valueOf(int value) {
return forNumber(value);
}
public static SuggestionCase forNumber(int value) {
switch (value) {
case 1:
return FREE_FORM_SUGGESTION;
case 2:
return SUMMARY_SUGGESTION;
case 0:
return SUGGESTION_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public SuggestionCase getSuggestionCase() {
return SuggestionCase.forNumber(suggestionCase_);
}
public static final int FREE_FORM_SUGGESTION_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the freeFormSuggestion field is set.
*/
@java.lang.Override
public boolean hasFreeFormSuggestion() {
return suggestionCase_ == 1;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The freeFormSuggestion.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.FreeFormSuggestion getFreeFormSuggestion() {
if (suggestionCase_ == 1) {
return (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.FreeFormSuggestionOrBuilder
getFreeFormSuggestionOrBuilder() {
if (suggestionCase_ == 1) {
return (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
}
public static final int SUMMARY_SUGGESTION_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the summarySuggestion field is set.
*/
@java.lang.Override
public boolean hasSummarySuggestion() {
return suggestionCase_ == 2;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The summarySuggestion.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SummarySuggestion getSummarySuggestion() {
if (suggestionCase_ == 2) {
return (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance();
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SummarySuggestionOrBuilder getSummarySuggestionOrBuilder() {
if (suggestionCase_ == 2) {
return (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.SummarySuggestion.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 (suggestionCase_ == 1) {
output.writeMessage(1, (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_);
}
if (suggestionCase_ == 2) {
output.writeMessage(2, (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (suggestionCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_);
}
if (suggestionCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2.GeneratorSuggestion)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.GeneratorSuggestion other =
(com.google.cloud.dialogflow.v2.GeneratorSuggestion) obj;
if (!getSuggestionCase().equals(other.getSuggestionCase())) return false;
switch (suggestionCase_) {
case 1:
if (!getFreeFormSuggestion().equals(other.getFreeFormSuggestion())) return false;
break;
case 2:
if (!getSummarySuggestion().equals(other.getSummarySuggestion())) 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 (suggestionCase_) {
case 1:
hash = (37 * hash) + FREE_FORM_SUGGESTION_FIELD_NUMBER;
hash = (53 * hash) + getFreeFormSuggestion().hashCode();
break;
case 2:
hash = (37 * hash) + SUMMARY_SUGGESTION_FIELD_NUMBER;
hash = (53 * hash) + getSummarySuggestion().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dialogflow.v2.GeneratorSuggestion 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>
* Suggestion generated using a Generator.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.GeneratorSuggestion}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.GeneratorSuggestion)
com.google.cloud.dialogflow.v2.GeneratorSuggestionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.GeneratorProto
.internal_static_google_cloud_dialogflow_v2_GeneratorSuggestion_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.GeneratorProto
.internal_static_google_cloud_dialogflow_v2_GeneratorSuggestion_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.GeneratorSuggestion.class,
com.google.cloud.dialogflow.v2.GeneratorSuggestion.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.GeneratorSuggestion.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (freeFormSuggestionBuilder_ != null) {
freeFormSuggestionBuilder_.clear();
}
if (summarySuggestionBuilder_ != null) {
summarySuggestionBuilder_.clear();
}
suggestionCase_ = 0;
suggestion_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.GeneratorProto
.internal_static_google_cloud_dialogflow_v2_GeneratorSuggestion_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GeneratorSuggestion getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.GeneratorSuggestion.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GeneratorSuggestion build() {
com.google.cloud.dialogflow.v2.GeneratorSuggestion result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GeneratorSuggestion buildPartial() {
com.google.cloud.dialogflow.v2.GeneratorSuggestion result =
new com.google.cloud.dialogflow.v2.GeneratorSuggestion(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dialogflow.v2.GeneratorSuggestion result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.dialogflow.v2.GeneratorSuggestion result) {
result.suggestionCase_ = suggestionCase_;
result.suggestion_ = this.suggestion_;
if (suggestionCase_ == 1 && freeFormSuggestionBuilder_ != null) {
result.suggestion_ = freeFormSuggestionBuilder_.build();
}
if (suggestionCase_ == 2 && summarySuggestionBuilder_ != null) {
result.suggestion_ = summarySuggestionBuilder_.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.dialogflow.v2.GeneratorSuggestion) {
return mergeFrom((com.google.cloud.dialogflow.v2.GeneratorSuggestion) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.GeneratorSuggestion other) {
if (other == com.google.cloud.dialogflow.v2.GeneratorSuggestion.getDefaultInstance())
return this;
switch (other.getSuggestionCase()) {
case FREE_FORM_SUGGESTION:
{
mergeFreeFormSuggestion(other.getFreeFormSuggestion());
break;
}
case SUMMARY_SUGGESTION:
{
mergeSummarySuggestion(other.getSummarySuggestion());
break;
}
case SUGGESTION_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getFreeFormSuggestionFieldBuilder().getBuilder(), extensionRegistry);
suggestionCase_ = 1;
break;
} // case 10
case 18:
{
input.readMessage(
getSummarySuggestionFieldBuilder().getBuilder(), extensionRegistry);
suggestionCase_ = 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 suggestionCase_ = 0;
private java.lang.Object suggestion_;
public SuggestionCase getSuggestionCase() {
return SuggestionCase.forNumber(suggestionCase_);
}
public Builder clearSuggestion() {
suggestionCase_ = 0;
suggestion_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.FreeFormSuggestion,
com.google.cloud.dialogflow.v2.FreeFormSuggestion.Builder,
com.google.cloud.dialogflow.v2.FreeFormSuggestionOrBuilder>
freeFormSuggestionBuilder_;
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the freeFormSuggestion field is set.
*/
@java.lang.Override
public boolean hasFreeFormSuggestion() {
return suggestionCase_ == 1;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The freeFormSuggestion.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.FreeFormSuggestion getFreeFormSuggestion() {
if (freeFormSuggestionBuilder_ == null) {
if (suggestionCase_ == 1) {
return (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
} else {
if (suggestionCase_ == 1) {
return freeFormSuggestionBuilder_.getMessage();
}
return com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setFreeFormSuggestion(com.google.cloud.dialogflow.v2.FreeFormSuggestion value) {
if (freeFormSuggestionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
suggestion_ = value;
onChanged();
} else {
freeFormSuggestionBuilder_.setMessage(value);
}
suggestionCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setFreeFormSuggestion(
com.google.cloud.dialogflow.v2.FreeFormSuggestion.Builder builderForValue) {
if (freeFormSuggestionBuilder_ == null) {
suggestion_ = builderForValue.build();
onChanged();
} else {
freeFormSuggestionBuilder_.setMessage(builderForValue.build());
}
suggestionCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeFreeFormSuggestion(
com.google.cloud.dialogflow.v2.FreeFormSuggestion value) {
if (freeFormSuggestionBuilder_ == null) {
if (suggestionCase_ == 1
&& suggestion_
!= com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance()) {
suggestion_ =
com.google.cloud.dialogflow.v2.FreeFormSuggestion.newBuilder(
(com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_)
.mergeFrom(value)
.buildPartial();
} else {
suggestion_ = value;
}
onChanged();
} else {
if (suggestionCase_ == 1) {
freeFormSuggestionBuilder_.mergeFrom(value);
} else {
freeFormSuggestionBuilder_.setMessage(value);
}
}
suggestionCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearFreeFormSuggestion() {
if (freeFormSuggestionBuilder_ == null) {
if (suggestionCase_ == 1) {
suggestionCase_ = 0;
suggestion_ = null;
onChanged();
}
} else {
if (suggestionCase_ == 1) {
suggestionCase_ = 0;
suggestion_ = null;
}
freeFormSuggestionBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dialogflow.v2.FreeFormSuggestion.Builder
getFreeFormSuggestionBuilder() {
return getFreeFormSuggestionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.FreeFormSuggestionOrBuilder
getFreeFormSuggestionOrBuilder() {
if ((suggestionCase_ == 1) && (freeFormSuggestionBuilder_ != null)) {
return freeFormSuggestionBuilder_.getMessageOrBuilder();
} else {
if (suggestionCase_ == 1) {
return (com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Free form suggestion.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.FreeFormSuggestion free_form_suggestion = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.FreeFormSuggestion,
com.google.cloud.dialogflow.v2.FreeFormSuggestion.Builder,
com.google.cloud.dialogflow.v2.FreeFormSuggestionOrBuilder>
getFreeFormSuggestionFieldBuilder() {
if (freeFormSuggestionBuilder_ == null) {
if (!(suggestionCase_ == 1)) {
suggestion_ = com.google.cloud.dialogflow.v2.FreeFormSuggestion.getDefaultInstance();
}
freeFormSuggestionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.FreeFormSuggestion,
com.google.cloud.dialogflow.v2.FreeFormSuggestion.Builder,
com.google.cloud.dialogflow.v2.FreeFormSuggestionOrBuilder>(
(com.google.cloud.dialogflow.v2.FreeFormSuggestion) suggestion_,
getParentForChildren(),
isClean());
suggestion_ = null;
}
suggestionCase_ = 1;
onChanged();
return freeFormSuggestionBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.SummarySuggestion,
com.google.cloud.dialogflow.v2.SummarySuggestion.Builder,
com.google.cloud.dialogflow.v2.SummarySuggestionOrBuilder>
summarySuggestionBuilder_;
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the summarySuggestion field is set.
*/
@java.lang.Override
public boolean hasSummarySuggestion() {
return suggestionCase_ == 2;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The summarySuggestion.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SummarySuggestion getSummarySuggestion() {
if (summarySuggestionBuilder_ == null) {
if (suggestionCase_ == 2) {
return (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance();
} else {
if (suggestionCase_ == 2) {
return summarySuggestionBuilder_.getMessage();
}
return com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setSummarySuggestion(com.google.cloud.dialogflow.v2.SummarySuggestion value) {
if (summarySuggestionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
suggestion_ = value;
onChanged();
} else {
summarySuggestionBuilder_.setMessage(value);
}
suggestionCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setSummarySuggestion(
com.google.cloud.dialogflow.v2.SummarySuggestion.Builder builderForValue) {
if (summarySuggestionBuilder_ == null) {
suggestion_ = builderForValue.build();
onChanged();
} else {
summarySuggestionBuilder_.setMessage(builderForValue.build());
}
suggestionCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeSummarySuggestion(com.google.cloud.dialogflow.v2.SummarySuggestion value) {
if (summarySuggestionBuilder_ == null) {
if (suggestionCase_ == 2
&& suggestion_
!= com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance()) {
suggestion_ =
com.google.cloud.dialogflow.v2.SummarySuggestion.newBuilder(
(com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_)
.mergeFrom(value)
.buildPartial();
} else {
suggestion_ = value;
}
onChanged();
} else {
if (suggestionCase_ == 2) {
summarySuggestionBuilder_.mergeFrom(value);
} else {
summarySuggestionBuilder_.setMessage(value);
}
}
suggestionCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearSummarySuggestion() {
if (summarySuggestionBuilder_ == null) {
if (suggestionCase_ == 2) {
suggestionCase_ = 0;
suggestion_ = null;
onChanged();
}
} else {
if (suggestionCase_ == 2) {
suggestionCase_ = 0;
suggestion_ = null;
}
summarySuggestionBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dialogflow.v2.SummarySuggestion.Builder getSummarySuggestionBuilder() {
return getSummarySuggestionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2.SummarySuggestionOrBuilder
getSummarySuggestionOrBuilder() {
if ((suggestionCase_ == 2) && (summarySuggestionBuilder_ != null)) {
return summarySuggestionBuilder_.getMessageOrBuilder();
} else {
if (suggestionCase_ == 2) {
return (com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_;
}
return com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Suggested summary.
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2.SummarySuggestion summary_suggestion = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.SummarySuggestion,
com.google.cloud.dialogflow.v2.SummarySuggestion.Builder,
com.google.cloud.dialogflow.v2.SummarySuggestionOrBuilder>
getSummarySuggestionFieldBuilder() {
if (summarySuggestionBuilder_ == null) {
if (!(suggestionCase_ == 2)) {
suggestion_ = com.google.cloud.dialogflow.v2.SummarySuggestion.getDefaultInstance();
}
summarySuggestionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2.SummarySuggestion,
com.google.cloud.dialogflow.v2.SummarySuggestion.Builder,
com.google.cloud.dialogflow.v2.SummarySuggestionOrBuilder>(
(com.google.cloud.dialogflow.v2.SummarySuggestion) suggestion_,
getParentForChildren(),
isClean());
suggestion_ = null;
}
suggestionCase_ = 2;
onChanged();
return summarySuggestionBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.GeneratorSuggestion)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.GeneratorSuggestion)
private static final com.google.cloud.dialogflow.v2.GeneratorSuggestion DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.GeneratorSuggestion();
}
public static com.google.cloud.dialogflow.v2.GeneratorSuggestion getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GeneratorSuggestion> PARSER =
new com.google.protobuf.AbstractParser<GeneratorSuggestion>() {
@java.lang.Override
public GeneratorSuggestion 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<GeneratorSuggestion> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GeneratorSuggestion> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GeneratorSuggestion getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 38,138 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteGlobalAddressRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for GlobalAddresses.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteGlobalAddressRequest}
*/
public final class DeleteGlobalAddressRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteGlobalAddressRequest)
DeleteGlobalAddressRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteGlobalAddressRequest.newBuilder() to construct.
private DeleteGlobalAddressRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteGlobalAddressRequest() {
address_ = "";
project_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteGlobalAddressRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteGlobalAddressRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteGlobalAddressRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteGlobalAddressRequest.class,
com.google.cloud.compute.v1.DeleteGlobalAddressRequest.Builder.class);
}
private int bitField0_;
public static final int ADDRESS_FIELD_NUMBER = 462920692;
@SuppressWarnings("serial")
private volatile java.lang.Object address_ = "";
/**
*
*
* <pre>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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 PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 37109963;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
@java.lang.Override
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(address_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 462920692, address_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(address_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(462920692, address_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.DeleteGlobalAddressRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.DeleteGlobalAddressRequest other =
(com.google.cloud.compute.v1.DeleteGlobalAddressRequest) obj;
if (!getAddress().equals(other.getAddress())) return false;
if (!getProject().equals(other.getProject())) return false;
if (hasRequestId() != other.hasRequestId()) return false;
if (hasRequestId()) {
if (!getRequestId().equals(other.getRequestId())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ADDRESS_FIELD_NUMBER;
hash = (53 * hash) + getAddress().hashCode();
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.DeleteGlobalAddressRequest 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 GlobalAddresses.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteGlobalAddressRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteGlobalAddressRequest)
com.google.cloud.compute.v1.DeleteGlobalAddressRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteGlobalAddressRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteGlobalAddressRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteGlobalAddressRequest.class,
com.google.cloud.compute.v1.DeleteGlobalAddressRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.DeleteGlobalAddressRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
address_ = "";
project_ = "";
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteGlobalAddressRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteGlobalAddressRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.DeleteGlobalAddressRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteGlobalAddressRequest build() {
com.google.cloud.compute.v1.DeleteGlobalAddressRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteGlobalAddressRequest buildPartial() {
com.google.cloud.compute.v1.DeleteGlobalAddressRequest result =
new com.google.cloud.compute.v1.DeleteGlobalAddressRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.DeleteGlobalAddressRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.address_ = address_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.requestId_ = requestId_;
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.DeleteGlobalAddressRequest) {
return mergeFrom((com.google.cloud.compute.v1.DeleteGlobalAddressRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.DeleteGlobalAddressRequest other) {
if (other == com.google.cloud.compute.v1.DeleteGlobalAddressRequest.getDefaultInstance())
return this;
if (!other.getAddress().isEmpty()) {
address_ = other.address_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasRequestId()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 296879706:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 296879706
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -591601758:
{
address_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case -591601758
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>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearAddress() {
address_ = getDefaultInstance().getAddress();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the address resource to delete.
* </pre>
*
* <code>string address = 462920692 [(.google.api.field_behavior) = REQUIRED];</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 project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteGlobalAddressRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteGlobalAddressRequest)
private static final com.google.cloud.compute.v1.DeleteGlobalAddressRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteGlobalAddressRequest();
}
public static com.google.cloud.compute.v1.DeleteGlobalAddressRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteGlobalAddressRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteGlobalAddressRequest>() {
@java.lang.Override
public DeleteGlobalAddressRequest 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<DeleteGlobalAddressRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteGlobalAddressRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteGlobalAddressRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/incubator-hugegraph | 38,217 | hugegraph-server/hugegraph-core/src/main/java/org/apache/hugegraph/util/collection/IntMapByDynamicHash.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.util.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import sun.misc.Unsafe;
/**
* This class implements a concurrent hash map specifically designed for integer keys and values.
* It uses low-level programming techniques such as direct memory access via `sun.misc.Unsafe` to
* achieve high performance.
* The class is part of the Apache HugeGraph project.
*/
public class IntMapByDynamicHash implements IntMap {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final float LOAD_FACTOR = 0.75f;
private static final int PARTITIONED_SIZE_THRESHOLD = 4096;
private static final int NULL_VALUE = Integer.MIN_VALUE;
private static final AtomicReferenceFieldUpdater<IntMapByDynamicHash, Entry[]>
TABLE_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(IntMapByDynamicHash.class, Entry[].class,
"table");
private volatile Entry[] table;
/**
* Partition counting to improve the concurrency performance of addToSize()
*/
private int[] partitionedSize;
/**
* updated via atomic field updater
*/
@SuppressWarnings("UnusedDeclaration")
private volatile int size;
private static final Entry RESIZING = new Entry(NULL_VALUE, NULL_VALUE, (byte) 1);
private static final Entry RESIZED = new Entry(NULL_VALUE, NULL_VALUE, (byte) 2);
private static final Entry RESIZE_SENTINEL = new Entry(NULL_VALUE, NULL_VALUE, (byte) 3);
/**
* must be (2^n) - 1
*/
private static final int SIZE_BUCKETS = 7;
/**
* Constructor for the IntMapByDynamicHash class.
*
* @param initialCapacity the initial capacity of the map.
*/
public IntMapByDynamicHash(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Initial Capacity: " + initialCapacity);
}
if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
}
long size = (long) (1.0 + (long) initialCapacity / LOAD_FACTOR);
int cap = (size >= (long) MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int) size);
if (cap >= PARTITIONED_SIZE_THRESHOLD) {
// we want 7 extra slots, and 64 bytes for each slot int are 4 bytes,
// so 64 bytes are 16 ints.
this.partitionedSize =
new int[SIZE_BUCKETS * 16];
}
// The end index is for resizeContainer
this.table = new Entry[cap + 1];
}
/**
* Default constructor for the IntMapByDynamicHash class.
* Initializes the map with the default initial capacity.
*/
public IntMapByDynamicHash() {
this(DEFAULT_INITIAL_CAPACITY);
}
private static void setTableAt(Object[] array, int index, Object newValue) {
UNSAFE.putObjectVolatile(array, ((long) index << ENTRY_ARRAY_SHIFT) + ENTRY_ARRAY_BASE,
newValue);
}
private static int tableSizeFor(int c) {
int n = c - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/* ---------------- Table element access -------------- */
private static long entryOffset(int index) {
return ((long) index << ENTRY_ARRAY_SHIFT) + ENTRY_ARRAY_BASE;
}
private static Object tableAt(Object[] array, int index) {
return UNSAFE.getObjectVolatile(array, entryOffset(index));
}
private static boolean casTableAt(Object[] array, int index, Object expected, Object newValue) {
return UNSAFE.compareAndSwapObject(array, entryOffset(index), expected, newValue);
}
/**
* Puts a key-value pair into the map. If the key already exists in the map, its value is
* updated.
*
* @param key the key to be put into the map.
* @param value the value to be associated with the key.
* @return true if the operation is successful.
*/
@Override
public boolean put(int key, int value) {
int hash = this.hash(key);
Entry[] currentArray = this.table;
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, hash);
if (o == null) {
Entry newEntry = new Entry(key, value);
this.addToSize(1);
if (IntMapByDynamicHash.casTableAt(currentArray, hash, null, newEntry)) {
return true;
}
this.addToSize(-1);
}
this.slowPut(key, value, currentArray);
return true;
}
/**
* This method is used when the normal put operation fails due to a hash collision.
* It searches for the key in the chain and if found, replaces the entry.
* If the key is not found, it adds a new entry.
*
* @param key the key to be put into the map.
* @param value the value to be associated with the key.
* @param currentTable the current table where the key-value pair is to be put.
* @return the old value if the key is already present in the map, otherwise NULL_VALUE.
*/
private int slowPut(int key, int value, Entry[] currentTable) {
int length;
int index;
Entry o;
while (true) {
length = currentTable.length;
index = this.hash(key, length);
o = (Entry) IntMapByDynamicHash.tableAt(currentTable, index);
if (o == RESIZED || o == RESIZING) {
currentTable = this.helpWithResizeWhileCurrentIndex(currentTable, index);
} else {
Entry e = o;
boolean found = false;
// Search for the key in the chain
while (e != null) {
int candidate = e.getKey();
if (candidate == key) {
found = true;
break;
}
e = e.getNext();
}
if (found) {
int oldVal = e.getValue();
// Key found, replace the entry
Entry newEntry =
new Entry(key, value, this.createReplacementChainForRemoval(o, e));
if (IntMapByDynamicHash.casTableAt(currentTable, index, o, newEntry)) {
return oldVal;
}
} else {
// Key not found, add a new entry
Entry newEntry = new Entry(key, value, o);
if (IntMapByDynamicHash.casTableAt(currentTable, index, o, newEntry)) {
this.incrementSizeAndPossiblyResize(currentTable, length, o);
return NULL_VALUE;
}
}
}
}
}
/**
* Retrieves the value associated with the given key from the map.
*
* @param key the key whose associated value is to be returned.
* @return the value associated with the given key, or NULL_VALUE if the key does not exist
* in the map.
*/
@Override
public int get(int key) {
int hash = this.hash(key);
Entry[] currentArray = this.table;
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, hash);
if (o == RESIZED || o == RESIZING) {
return this.slowGet(key, currentArray);
}
for (Entry e = o; e != null; e = e.getNext()) {
int k;
// TODO: check why key == k is always false
if ((k = e.getKey()) == key || key == k) {
return e.value;
}
}
return NULL_VALUE;
}
/**
* This method is used when the normal get operation fails due to a hash collision.
* It searches for the key in the chain and returns the associated value if found.
*
* @param key the key whose associated value is to be returned.
* @param currentArray the current table where the key-value pair is located.
* @return the value associated with the given key, or NULL_VALUE if the key does not exist
* in the map.
*/
private int slowGet(int key, Entry[] currentArray) {
while (true) {
int length = currentArray.length;
int hash = this.hash(key, length);
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, hash);
if (o == RESIZED || o == RESIZING) {
currentArray = this.helpWithResizeWhileCurrentIndex(currentArray, hash);
} else {
Entry e = o;
while (e != null) {
int candidate = e.getKey();
if (candidate == key) {
return e.getValue();
}
e = e.getNext();
}
return NULL_VALUE;
}
}
}
/**
* Removes the key-value pair with the given key from the map.
*
* @param key the key whose associated key-value pair is to be removed.
* @return true if the key-value pair was found and removed, false otherwise.
*/
@Override
public boolean remove(int key) {
int hash = this.hash(key);
Entry[] currentTable = this.table;
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentTable, hash);
if (o == RESIZED || o == RESIZING) {
return this.slowRemove(key, currentTable) != null;
}
Entry e = o;
while (e != null) {
int candidate = e.getKey();
if (candidate == key) {
Entry replacement = this.createReplacementChainForRemoval(o, e);
if (IntMapByDynamicHash.casTableAt(currentTable, hash, o, replacement)) {
this.addToSize(-1);
return true;
}
return this.slowRemove(key, currentTable) != null;
}
e = e.getNext();
}
return false;
}
/**
* This method is used when the normal remove operation fails due to a hash collision.
* It searches for the key in the chain and if found, removes the entry.
*
* @param key the key whose associated key-value pair is to be removed.
* @param currentTable the current table where the key-value pair is located.
* @return the removed entry if the key is found, otherwise null.
*/
private Entry slowRemove(int key, Entry[] currentTable) {
int length;
int index;
Entry o;
while (true) {
length = currentTable.length;
index = this.hash(key, length);
o = (Entry) IntMapByDynamicHash.tableAt(currentTable, index);
if (o == RESIZED || o == RESIZING) {
currentTable = this.helpWithResizeWhileCurrentIndex(currentTable, index);
} else {
Entry e = o;
Entry prev = null;
while (e != null) {
int candidate = e.getKey();
if (candidate == key) {
Entry replacement = this.createReplacementChainForRemoval(o, e);
if (IntMapByDynamicHash.casTableAt(currentTable, index, o, replacement)) {
this.addToSize(-1);
return e;
}
// Key found, but CAS failed, restart the loop
break;
}
prev = e;
e = e.getNext();
}
if (prev != null) {
// Key doesn't found
return null;
}
}
}
}
/**
* Checks if the map contains a key-value pair with the given key.
*
* @param key the key to be checked.
* @return true if the map contains a key-value pair with the given key, false otherwise.
*/
@Override
public boolean containsKey(int key) {
return this.getEntry(key) != null;
}
@Override
public IntIterator keys() {
return new KeyIterator();
}
@Override
public IntIterator values() {
return new ValueIterator();
}
/**
* Removes all the mappings from this map. The map will be empty after this call returns.
*/
@Override
public void clear() {
Entry[] currentArray = this.table;
ResizeContainer resizeContainer;
do {
resizeContainer = null;
for (int i = 0; i < currentArray.length - 1; i++) {
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, i);
if (o == RESIZED || o == RESIZING) {
resizeContainer =
(ResizeContainer) IntMapByDynamicHash.tableAt(currentArray,
currentArray.length - 1);
} else if (o != null) {
Entry e = o;
if (IntMapByDynamicHash.casTableAt(currentArray, i, o, null)) {
int removedEntries = 0;
while (e != null) {
removedEntries++;
e = e.getNext();
}
this.addToSize(-removedEntries);
}
}
}
if (resizeContainer != null) {
if (resizeContainer.isNotDone()) {
this.helpWithResize(currentArray);
resizeContainer.waitForAllResizers();
}
currentArray = resizeContainer.nextArray;
}
} while (resizeContainer != null);
}
@Override
public int size() {
int localSize = this.size;
if (this.partitionedSize != null) {
for (int i = 0; i < SIZE_BUCKETS; i++) {
localSize += this.partitionedSize[i << 4];
}
}
return localSize;
}
@Override
public boolean concurrent() {
return true;
}
private int hash(int key) {
return key & (table.length - 2);
}
private int hash(int key, int length) {
return key & (length - 2);
}
private Entry getEntry(int key) {
Entry[] currentArray = this.table;
while (true) {
int length = currentArray.length;
int index = this.hash(key, length);
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, index);
if (o == RESIZED || o == RESIZING) {
currentArray = this.helpWithResizeWhileCurrentIndex(currentArray, index);
} else {
Entry e = o;
while (e != null) {
int candidate = e.getKey();
if (candidate == key) {
return e;
}
e = e.getNext();
}
return null;
}
}
}
private void addToSize(int value) {
if (this.partitionedSize != null) {
if (this.incrementPartitionedSize(value)) {
return;
}
}
this.incrementLocalSize(value);
}
private boolean incrementPartitionedSize(int value) {
int h = (int) Thread.currentThread().getId();
h ^= (h >>> 18) ^ (h >>> 12);
h = (h ^ (h >>> 10)) & SIZE_BUCKETS;
if (h != 0) {
h = (h - 1) << 4;
long address = ((long) h << INT_ARRAY_SHIFT) + INT_ARRAY_BASE;
while (true) {
int localSize = UNSAFE.getIntVolatile(this.partitionedSize, address);
if (UNSAFE.compareAndSwapInt(this.partitionedSize, address, localSize,
localSize + value)) {
return true;
}
}
}
return false;
}
private void incrementLocalSize(int value) {
while (true) {
int localSize = this.size;
if (UNSAFE.compareAndSwapInt(this, SIZE_OFFSET, localSize, localSize + value)) {
break;
}
}
}
private Entry createReplacementChainForRemoval(Entry original, Entry toRemove) {
if (original == toRemove) {
return original.getNext();
}
Entry replacement = null;
Entry e = original;
while (e != null) {
if (e != toRemove) {
replacement = new Entry(e.getKey(), e.getValue(), replacement);
}
e = e.getNext();
}
return replacement;
}
private void incrementSizeAndPossiblyResize(Entry[] currentArray, int length, Entry prev) {
this.addToSize(1);
if (prev != null) {
int localSize = this.size();
int threshold = (int) (length * LOAD_FACTOR); // threshold = length * 0.75
if (localSize + 1 > threshold) {
this.resize(currentArray);
}
}
}
private Entry[] helpWithResizeWhileCurrentIndex(Entry[] currentArray, int index) {
Entry[] newArray = this.helpWithResize(currentArray);
int helpCount = 0;
while (IntMapByDynamicHash.tableAt(currentArray, index) != RESIZED) {
helpCount++;
newArray = this.helpWithResize(currentArray);
if ((helpCount & 7) == 0) {
Thread.yield();
}
}
return newArray;
}
private void resize(Entry[] oldTable) {
this.resize(oldTable, (oldTable.length - 1 << 1) + 1);
}
/**
* Resizes the map to a new capacity. This method is called when the map's size exceeds its
* threshold. It creates a new array with the new capacity and transfers all entries from the
* old array to the new one.
* Note: newSize must be a power of 2 + 1
*
* @param oldTable The old table to resize.
* @param newSize The new size for the table.
*/
@SuppressWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER")
private void resize(Entry[] oldTable, int newSize) {
int oldCapacity = oldTable.length;
int end = oldCapacity - 1;
Entry last = (Entry) IntMapByDynamicHash.tableAt(oldTable, end);
if (this.size() < end && last == RESIZE_SENTINEL) {
return;
}
if (oldCapacity >= MAXIMUM_CAPACITY) {
throw new RuntimeException("max capacity of map exceeded");
}
ResizeContainer resizeContainer = null;
// This ownResize records whether current thread need to perform the expansion operation of
// the map by itself
boolean ownResize = false;
if (last == null || last == RESIZE_SENTINEL) {
// allocating a new array is too expensive to make this an atomic operation
synchronized (oldTable) {
if (IntMapByDynamicHash.tableAt(oldTable, end) == null) {
IntMapByDynamicHash.setTableAt(oldTable, end, RESIZE_SENTINEL);
if (this.partitionedSize == null && newSize >= PARTITIONED_SIZE_THRESHOLD) {
this.partitionedSize = new int[SIZE_BUCKETS * 16];
}
resizeContainer = new ResizeContainer(new Entry[newSize], oldTable.length - 1);
IntMapByDynamicHash.setTableAt(oldTable, end, resizeContainer);
ownResize = true;
}
}
}
if (ownResize) {
this.transfer(oldTable, resizeContainer);
Entry[] src = this.table;
while (!TABLE_UPDATER.compareAndSet(this, oldTable, resizeContainer.nextArray)) {
/*
we're in a double resize situation; we'll have to go help until it's our turn
to set the table
*/
if (src != oldTable) {
this.helpWithResize(src);
}
}
} else {
this.helpWithResize(oldTable);
}
}
/**
* Transfers all entries from the source table to the destination table. This method is
* called during the resize operation. It iterates over the source table and for each non-null
* entry, it copies the entry to the destination table. If the entry in the source table is
* marked as RESIZED or RESIZING, it helps with the resize operation.
* After all entries are transferred, it notifies the ResizeContainer that the resize operation
* is done.
*
* @param src The source table from which entries are to be transferred.
* @param resizeContainer The container that holds the state of the resize operation.
*/
private void transfer(Entry[] src, ResizeContainer resizeContainer) {
Entry[] dest = resizeContainer.nextArray;
for (int j = 0; j < src.length - 1; ) {
Entry o = (Entry) IntMapByDynamicHash.tableAt(src, j);
if (o == null) {
if (IntMapByDynamicHash.casTableAt(src, j, null, RESIZED)) {
j++;
}
} else if (o == RESIZED || o == RESIZING) {
/*
During the expansion process, other threads have already migrated the elements at
this location to the new array. This means that the elements in the current
position have already been processed and do not need to be migrated again.
*/
j = (j & ~(ResizeContainer.QUEUE_INCREMENT - 1)) + ResizeContainer.QUEUE_INCREMENT;
/*
When there is only one thread for expansion, there is no concurrency issue
and there is no need to wait.
*/
if (resizeContainer.resizers.get() == 1) {
break;
}
} else {
Entry e = o;
if (IntMapByDynamicHash.casTableAt(src, j, o, RESIZING)) {
while (e != null) {
this.unconditionalCopy(dest, e);
e = e.getNext();
}
IntMapByDynamicHash.setTableAt(src, j, RESIZED);
j++;
}
}
}
resizeContainer.decrementResizerAndNotify();
resizeContainer.waitForAllResizers();
}
/**
* Enable the current thread to participate in the expansion
*/
private Entry[] helpWithResize(Entry[] currentArray) {
ResizeContainer resizeContainer =
(ResizeContainer) IntMapByDynamicHash.tableAt(currentArray,
currentArray.length - 1);
Entry[] newTable = resizeContainer.nextArray;
if (resizeContainer.getQueuePosition() > ResizeContainer.QUEUE_INCREMENT) {
resizeContainer.incrementResizer();
this.reverseTransfer(currentArray, resizeContainer);
resizeContainer.decrementResizerAndNotify();
}
return newTable;
}
/**
* Transfers entries from the old table to the new table in reverse order. This method is used
* to help the resize operation by spreading the work among multiple threads. Each thread
* transfers a portion of the entries from the end of the old table to the beginning of the new
* table.
*
* @param src The old table to transfer entries from.
* @param resizeContainer The container that holds the state of the resize operation.
*/
private void reverseTransfer(Entry[] src, ResizeContainer resizeContainer) {
Entry[] dest = resizeContainer.nextArray;
while (resizeContainer.getQueuePosition() > 0) {
int start = resizeContainer.subtractAndGetQueuePosition();
int end = start + ResizeContainer.QUEUE_INCREMENT;
if (end > 0) {
if (start < 0) {
start = 0;
}
for (int j = end - 1; j >= start; ) {
Entry o = (Entry) IntMapByDynamicHash.tableAt(src, j);
if (o == null) {
if (IntMapByDynamicHash.casTableAt(src, j, null, RESIZED)) {
j--;
}
} else if (o == RESIZED || o == RESIZING) {
resizeContainer.zeroOutQueuePosition();
return;
} else {
Entry e = o;
if (IntMapByDynamicHash.casTableAt(src, j, o, RESIZING)) {
while (e != null) {
this.unconditionalCopy(dest, e);
e = e.getNext();
}
IntMapByDynamicHash.setTableAt(src, j, RESIZED);
j--;
}
}
}
}
}
}
/**
* Copies an entry from the old table to the new table. This method is called during the resize
* operation. It does not check if the entry already exists in the new table, so it should only
* be called with entries that are not in the new table yet.
*
* @param dest The new table to copy the entry to.
* @param toCopyEntry The entry to copy.
*/
private void unconditionalCopy(Entry[] dest, Entry toCopyEntry) {
Entry[] currentArray = dest;
while (true) {
int length = currentArray.length;
int index = this.hash(toCopyEntry.getKey(), length);
Entry o = (Entry) IntMapByDynamicHash.tableAt(currentArray, index);
if (o == RESIZED || o == RESIZING) {
currentArray =
((ResizeContainer) IntMapByDynamicHash.tableAt(currentArray,
length - 1)).nextArray;
} else {
Entry newEntry;
if (o == null) {
if (toCopyEntry.getNext() == null) {
newEntry = toCopyEntry; // no need to duplicate
} else {
newEntry = new Entry(toCopyEntry.getKey(), toCopyEntry.getValue());
}
} else {
newEntry = new Entry(toCopyEntry.getKey(), toCopyEntry.getValue(), o);
}
if (IntMapByDynamicHash.casTableAt(currentArray, index, o, newEntry)) {
return;
}
}
}
}
/**
* The ResizeContainer class is used to hold the state of the resize operation.
* It contains the new array to which entries are transferred, the number of threads
* participating in the resize operation, and the position in the old array from which
* entries are transferred.
*/
private static final class ResizeContainer extends Entry {
private static final int QUEUE_INCREMENT =
Math.min(1 << 10,
Integer.highestOneBit(IntSet.CPUS) << 4);
private final AtomicInteger resizers = new AtomicInteger(1);
private final Entry[] nextArray;
private final AtomicInteger queuePosition;
private ResizeContainer(Entry[] nextArray, int oldSize) {
super(NULL_VALUE, NULL_VALUE, (byte) 4);
this.nextArray = nextArray;
this.queuePosition = new AtomicInteger(oldSize);
}
public void incrementResizer() {
this.resizers.incrementAndGet();
}
public void decrementResizerAndNotify() {
int remaining = this.resizers.decrementAndGet();
if (remaining == 0) {
synchronized (this) {
this.notifyAll();
}
}
}
public int getQueuePosition() {
return this.queuePosition.get();
}
public int subtractAndGetQueuePosition() {
return this.queuePosition.addAndGet(-QUEUE_INCREMENT);
}
public void waitForAllResizers() {
if (this.resizers.get() > 0) {
for (int i = 0; i < 16; i++) {
if (this.resizers.get() == 0) {
break;
}
}
for (int i = 0; i < 16; i++) {
if (this.resizers.get() == 0) {
break;
}
Thread.yield();
}
}
if (this.resizers.get() > 0) {
synchronized (this) {
while (this.resizers.get() > 0) {
try {
this.wait();
} catch (InterruptedException e) {
// ignore
}
}
}
}
}
public boolean isNotDone() {
return this.resizers.get() > 0;
}
public void zeroOutQueuePosition() {
this.queuePosition.set(0);
}
}
private static class Entry {
final int key;
volatile int value;
volatile Entry next;
/**
* 0 NORMAL
* 1 RESIZING
* 2 RESIZED
* 3 RESIZE_SENTINEL
* 4 RESIZE_CONTAINER
*/
final byte state;
public Entry(int key, int value, byte state) {
this.key = key;
this.value = value;
this.state = state;
}
public Entry(int key, int value) {
this.key = key;
this.value = value;
this.next = null;
this.state = 0;
}
public Entry(int key, int value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
this.state = 0;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public Entry getNext() {
return next;
}
@Override
public String toString() {
return this.key + "=" + this.value;
}
}
/* ---------------- Iterator -------------- */
private static final class IteratorState {
private Entry[] currentTable;
private int start;
private int end;
private IteratorState(Entry[] currentTable) {
this.currentTable = currentTable;
this.end = this.currentTable.length - 1;
}
private IteratorState(Entry[] currentTable, int start, int end) {
this.currentTable = currentTable;
this.start = start;
this.end = end;
}
}
/**
* The HashIterator class is an abstract base class for iterators over the map.
* It maintains the current state of the iteration, which includes the current table
* being iterated over and the index of the next entry to be returned.
* The findNext() method is used to advance the iterator to the next entry.
*/
private abstract class HashIterator implements IntIterator {
private List<IteratorState> todo;
private IteratorState currentState;
private Entry next;
private int index;
protected HashIterator() {
this.currentState = new IteratorState(IntMapByDynamicHash.this.table);
this.findNext();
}
/**
* This method is used to advance the iterator to the next entry.
* It iterates over the entries in the current table from the current index
* until it finds a non-null entry. If it encounters a RESIZED or RESIZING entry,
* it helps with the resize operation and continues the iteration in the new table.
* If it reaches the end of the current table and there are still tables left to be
* iterated over, it switches to the next table.
*/
private void findNext() {
while (this.index < this.currentState.end) {
Entry o =
(Entry) IntMapByDynamicHash.tableAt(this.currentState.currentTable,
this.index);
if (o == RESIZED || o == RESIZING) {
Entry[] nextArray =
IntMapByDynamicHash.this.helpWithResizeWhileCurrentIndex(
this.currentState.currentTable, this.index);
int endResized = this.index + 1;
while (endResized < this.currentState.end) {
if (IntMapByDynamicHash.tableAt(this.currentState.currentTable,
endResized) != RESIZED) {
break;
}
endResized++;
}
if (this.todo == null) {
this.todo = new ArrayList<>(4);
}
if (endResized < this.currentState.end) {
this.todo.add(new IteratorState(
this.currentState.currentTable, endResized, this.currentState.end));
}
int powerTwoLength = this.currentState.currentTable.length - 1;
this.todo.add(new IteratorState(nextArray, this.index + powerTwoLength,
endResized + powerTwoLength));
this.currentState.currentTable = nextArray;
this.currentState.end = endResized;
this.currentState.start = this.index;
} else if (o != null) {
this.next = o;
this.index++;
break;
} else {
this.index++;
}
}
if (this.next == null && this.index == this.currentState.end && this.todo != null &&
!this.todo.isEmpty()) {
this.currentState = this.todo.remove(this.todo.size() - 1);
this.index = this.currentState.start;
this.findNext();
}
}
@Override
public final boolean hasNext() {
return this.next != null;
}
final Entry nextEntry() {
Entry e = this.next;
if (e == null) {
throw new NoSuchElementException();
}
if ((this.next = e.getNext()) == null) {
this.findNext();
}
return e;
}
}
private final class ValueIterator extends HashIterator {
@Override
public int next() {
return this.nextEntry().getValue();
}
}
private final class KeyIterator extends HashIterator {
@Override
public int next() {
return this.nextEntry().getKey();
}
}
/* ---------------- Unsafe mechanics -------------- */
private static final Unsafe UNSAFE = IntSet.UNSAFE;
private static final long ENTRY_ARRAY_BASE;
private static final int ENTRY_ARRAY_SHIFT;
private static final long INT_ARRAY_BASE;
private static final int INT_ARRAY_SHIFT;
private static final long SIZE_OFFSET;
static {
try {
Class<?> tableClass = Entry[].class;
ENTRY_ARRAY_BASE = UNSAFE.arrayBaseOffset(tableClass);
int objectArrayScale = UNSAFE.arrayIndexScale(tableClass);
if ((objectArrayScale & (objectArrayScale - 1)) != 0) {
throw new AssertionError("data type scale not a power of two");
}
ENTRY_ARRAY_SHIFT = 31 - Integer.numberOfLeadingZeros(objectArrayScale);
Class<?> intArrayClass = int[].class;
INT_ARRAY_BASE = UNSAFE.arrayBaseOffset(intArrayClass);
int intArrayScale = UNSAFE.arrayIndexScale(intArrayClass);
if ((intArrayScale & (intArrayScale - 1)) != 0) {
throw new AssertionError("data type scale not a power of two");
}
INT_ARRAY_SHIFT = 31 - Integer.numberOfLeadingZeros(intArrayScale);
Class<?> mapClass = IntMapByDynamicHash.class;
SIZE_OFFSET = UNSAFE.objectFieldOffset(mapClass.getDeclaredField("size"));
} catch (NoSuchFieldException | SecurityException e) {
throw new AssertionError(e);
}
}
}
|
googleads/google-ads-java | 38,221 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/ProductMetadata.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/services/reach_plan_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.services;
/**
* <pre>
* The metadata associated with an available plannable product.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.ProductMetadata}
*/
public final class ProductMetadata extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.ProductMetadata)
ProductMetadataOrBuilder {
private static final long serialVersionUID = 0L;
// Use ProductMetadata.newBuilder() to construct.
private ProductMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ProductMetadata() {
plannableProductCode_ = "";
plannableProductName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ProductMetadata();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ProductMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ProductMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.ProductMetadata.class, com.google.ads.googleads.v19.services.ProductMetadata.Builder.class);
}
private int bitField0_;
public static final int PLANNABLE_PRODUCT_CODE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object plannableProductCode_ = "";
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return Whether the plannableProductCode field is set.
*/
@java.lang.Override
public boolean hasPlannableProductCode() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The plannableProductCode.
*/
@java.lang.Override
public java.lang.String getPlannableProductCode() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductCode_ = s;
return s;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The bytes for plannableProductCode.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPlannableProductCodeBytes() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PLANNABLE_PRODUCT_NAME_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object plannableProductName_ = "";
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The plannableProductName.
*/
@java.lang.Override
public java.lang.String getPlannableProductName() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductName_ = s;
return s;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The bytes for plannableProductName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPlannableProductNameBytes() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PLANNABLE_TARGETING_FIELD_NUMBER = 2;
private com.google.ads.googleads.v19.services.PlannableTargeting plannableTargeting_;
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
* @return Whether the plannableTargeting field is set.
*/
@java.lang.Override
public boolean hasPlannableTargeting() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
* @return The plannableTargeting.
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.PlannableTargeting getPlannableTargeting() {
return plannableTargeting_ == null ? com.google.ads.googleads.v19.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.PlannableTargetingOrBuilder getPlannableTargetingOrBuilder() {
return plannableTargeting_ == null ? com.google.ads.googleads.v19.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getPlannableTargeting());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(plannableProductName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, plannableProductName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, plannableProductCode_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getPlannableTargeting());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(plannableProductName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, plannableProductName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, plannableProductCode_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.services.ProductMetadata)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.services.ProductMetadata other = (com.google.ads.googleads.v19.services.ProductMetadata) obj;
if (hasPlannableProductCode() != other.hasPlannableProductCode()) return false;
if (hasPlannableProductCode()) {
if (!getPlannableProductCode()
.equals(other.getPlannableProductCode())) return false;
}
if (!getPlannableProductName()
.equals(other.getPlannableProductName())) return false;
if (hasPlannableTargeting() != other.hasPlannableTargeting()) return false;
if (hasPlannableTargeting()) {
if (!getPlannableTargeting()
.equals(other.getPlannableTargeting())) 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 (hasPlannableProductCode()) {
hash = (37 * hash) + PLANNABLE_PRODUCT_CODE_FIELD_NUMBER;
hash = (53 * hash) + getPlannableProductCode().hashCode();
}
hash = (37 * hash) + PLANNABLE_PRODUCT_NAME_FIELD_NUMBER;
hash = (53 * hash) + getPlannableProductName().hashCode();
if (hasPlannableTargeting()) {
hash = (37 * hash) + PLANNABLE_TARGETING_FIELD_NUMBER;
hash = (53 * hash) + getPlannableTargeting().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ProductMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.services.ProductMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The metadata associated with an available plannable product.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.ProductMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.ProductMetadata)
com.google.ads.googleads.v19.services.ProductMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ProductMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ProductMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.ProductMetadata.class, com.google.ads.googleads.v19.services.ProductMetadata.Builder.class);
}
// Construct using com.google.ads.googleads.v19.services.ProductMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getPlannableTargetingFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
plannableProductCode_ = "";
plannableProductName_ = "";
plannableTargeting_ = null;
if (plannableTargetingBuilder_ != null) {
plannableTargetingBuilder_.dispose();
plannableTargetingBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ProductMetadata_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ProductMetadata getDefaultInstanceForType() {
return com.google.ads.googleads.v19.services.ProductMetadata.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ProductMetadata build() {
com.google.ads.googleads.v19.services.ProductMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ProductMetadata buildPartial() {
com.google.ads.googleads.v19.services.ProductMetadata result = new com.google.ads.googleads.v19.services.ProductMetadata(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.services.ProductMetadata result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.plannableProductCode_ = plannableProductCode_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.plannableProductName_ = plannableProductName_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.plannableTargeting_ = plannableTargetingBuilder_ == null
? plannableTargeting_
: plannableTargetingBuilder_.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.ads.googleads.v19.services.ProductMetadata) {
return mergeFrom((com.google.ads.googleads.v19.services.ProductMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.services.ProductMetadata other) {
if (other == com.google.ads.googleads.v19.services.ProductMetadata.getDefaultInstance()) return this;
if (other.hasPlannableProductCode()) {
plannableProductCode_ = other.plannableProductCode_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getPlannableProductName().isEmpty()) {
plannableProductName_ = other.plannableProductName_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasPlannableTargeting()) {
mergePlannableTargeting(other.getPlannableTargeting());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 18: {
input.readMessage(
getPlannableTargetingFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 18
case 26: {
plannableProductName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 26
case 34: {
plannableProductCode_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 34
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object plannableProductCode_ = "";
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return Whether the plannableProductCode field is set.
*/
public boolean hasPlannableProductCode() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The plannableProductCode.
*/
public java.lang.String getPlannableProductCode() {
java.lang.Object ref = plannableProductCode_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductCode_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The bytes for plannableProductCode.
*/
public com.google.protobuf.ByteString
getPlannableProductCodeBytes() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @param value The plannableProductCode to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductCode(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
plannableProductCode_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return This builder for chaining.
*/
public Builder clearPlannableProductCode() {
plannableProductCode_ = getDefaultInstance().getPlannableProductCode();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v19.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @param value The bytes for plannableProductCode to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductCodeBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
plannableProductCode_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object plannableProductName_ = "";
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The plannableProductName.
*/
public java.lang.String getPlannableProductName() {
java.lang.Object ref = plannableProductName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The bytes for plannableProductName.
*/
public com.google.protobuf.ByteString
getPlannableProductNameBytes() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @param value The plannableProductName to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
plannableProductName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPlannableProductName() {
plannableProductName_ = getDefaultInstance().getPlannableProductName();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @param value The bytes for plannableProductName to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
plannableProductName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.ads.googleads.v19.services.PlannableTargeting plannableTargeting_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.PlannableTargeting, com.google.ads.googleads.v19.services.PlannableTargeting.Builder, com.google.ads.googleads.v19.services.PlannableTargetingOrBuilder> plannableTargetingBuilder_;
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
* @return Whether the plannableTargeting field is set.
*/
public boolean hasPlannableTargeting() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
* @return The plannableTargeting.
*/
public com.google.ads.googleads.v19.services.PlannableTargeting getPlannableTargeting() {
if (plannableTargetingBuilder_ == null) {
return plannableTargeting_ == null ? com.google.ads.googleads.v19.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
} else {
return plannableTargetingBuilder_.getMessage();
}
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder setPlannableTargeting(com.google.ads.googleads.v19.services.PlannableTargeting value) {
if (plannableTargetingBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
plannableTargeting_ = value;
} else {
plannableTargetingBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder setPlannableTargeting(
com.google.ads.googleads.v19.services.PlannableTargeting.Builder builderForValue) {
if (plannableTargetingBuilder_ == null) {
plannableTargeting_ = builderForValue.build();
} else {
plannableTargetingBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder mergePlannableTargeting(com.google.ads.googleads.v19.services.PlannableTargeting value) {
if (plannableTargetingBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0) &&
plannableTargeting_ != null &&
plannableTargeting_ != com.google.ads.googleads.v19.services.PlannableTargeting.getDefaultInstance()) {
getPlannableTargetingBuilder().mergeFrom(value);
} else {
plannableTargeting_ = value;
}
} else {
plannableTargetingBuilder_.mergeFrom(value);
}
if (plannableTargeting_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder clearPlannableTargeting() {
bitField0_ = (bitField0_ & ~0x00000004);
plannableTargeting_ = null;
if (plannableTargetingBuilder_ != null) {
plannableTargetingBuilder_.dispose();
plannableTargetingBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public com.google.ads.googleads.v19.services.PlannableTargeting.Builder getPlannableTargetingBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getPlannableTargetingFieldBuilder().getBuilder();
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public com.google.ads.googleads.v19.services.PlannableTargetingOrBuilder getPlannableTargetingOrBuilder() {
if (plannableTargetingBuilder_ != null) {
return plannableTargetingBuilder_.getMessageOrBuilder();
} else {
return plannableTargeting_ == null ?
com.google.ads.googleads.v19.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v19.services.PlannableTargeting plannable_targeting = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.PlannableTargeting, com.google.ads.googleads.v19.services.PlannableTargeting.Builder, com.google.ads.googleads.v19.services.PlannableTargetingOrBuilder>
getPlannableTargetingFieldBuilder() {
if (plannableTargetingBuilder_ == null) {
plannableTargetingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.PlannableTargeting, com.google.ads.googleads.v19.services.PlannableTargeting.Builder, com.google.ads.googleads.v19.services.PlannableTargetingOrBuilder>(
getPlannableTargeting(),
getParentForChildren(),
isClean());
plannableTargeting_ = null;
}
return plannableTargetingBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.services.ProductMetadata)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.ProductMetadata)
private static final com.google.ads.googleads.v19.services.ProductMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.ProductMetadata();
}
public static com.google.ads.googleads.v19.services.ProductMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ProductMetadata>
PARSER = new com.google.protobuf.AbstractParser<ProductMetadata>() {
@java.lang.Override
public ProductMetadata 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<ProductMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ProductMetadata> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ProductMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 38,221 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/ProductMetadata.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/services/reach_plan_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.services;
/**
* <pre>
* The metadata associated with an available plannable product.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.ProductMetadata}
*/
public final class ProductMetadata extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.ProductMetadata)
ProductMetadataOrBuilder {
private static final long serialVersionUID = 0L;
// Use ProductMetadata.newBuilder() to construct.
private ProductMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ProductMetadata() {
plannableProductCode_ = "";
plannableProductName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ProductMetadata();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ProductMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ProductMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.ProductMetadata.class, com.google.ads.googleads.v20.services.ProductMetadata.Builder.class);
}
private int bitField0_;
public static final int PLANNABLE_PRODUCT_CODE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object plannableProductCode_ = "";
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return Whether the plannableProductCode field is set.
*/
@java.lang.Override
public boolean hasPlannableProductCode() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The plannableProductCode.
*/
@java.lang.Override
public java.lang.String getPlannableProductCode() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductCode_ = s;
return s;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The bytes for plannableProductCode.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPlannableProductCodeBytes() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PLANNABLE_PRODUCT_NAME_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object plannableProductName_ = "";
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The plannableProductName.
*/
@java.lang.Override
public java.lang.String getPlannableProductName() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductName_ = s;
return s;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The bytes for plannableProductName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPlannableProductNameBytes() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PLANNABLE_TARGETING_FIELD_NUMBER = 2;
private com.google.ads.googleads.v20.services.PlannableTargeting plannableTargeting_;
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
* @return Whether the plannableTargeting field is set.
*/
@java.lang.Override
public boolean hasPlannableTargeting() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
* @return The plannableTargeting.
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.PlannableTargeting getPlannableTargeting() {
return plannableTargeting_ == null ? com.google.ads.googleads.v20.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.PlannableTargetingOrBuilder getPlannableTargetingOrBuilder() {
return plannableTargeting_ == null ? com.google.ads.googleads.v20.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getPlannableTargeting());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(plannableProductName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, plannableProductName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, plannableProductCode_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getPlannableTargeting());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(plannableProductName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, plannableProductName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, plannableProductCode_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.services.ProductMetadata)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.services.ProductMetadata other = (com.google.ads.googleads.v20.services.ProductMetadata) obj;
if (hasPlannableProductCode() != other.hasPlannableProductCode()) return false;
if (hasPlannableProductCode()) {
if (!getPlannableProductCode()
.equals(other.getPlannableProductCode())) return false;
}
if (!getPlannableProductName()
.equals(other.getPlannableProductName())) return false;
if (hasPlannableTargeting() != other.hasPlannableTargeting()) return false;
if (hasPlannableTargeting()) {
if (!getPlannableTargeting()
.equals(other.getPlannableTargeting())) 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 (hasPlannableProductCode()) {
hash = (37 * hash) + PLANNABLE_PRODUCT_CODE_FIELD_NUMBER;
hash = (53 * hash) + getPlannableProductCode().hashCode();
}
hash = (37 * hash) + PLANNABLE_PRODUCT_NAME_FIELD_NUMBER;
hash = (53 * hash) + getPlannableProductName().hashCode();
if (hasPlannableTargeting()) {
hash = (37 * hash) + PLANNABLE_TARGETING_FIELD_NUMBER;
hash = (53 * hash) + getPlannableTargeting().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ProductMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.services.ProductMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The metadata associated with an available plannable product.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.ProductMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.ProductMetadata)
com.google.ads.googleads.v20.services.ProductMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ProductMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ProductMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.ProductMetadata.class, com.google.ads.googleads.v20.services.ProductMetadata.Builder.class);
}
// Construct using com.google.ads.googleads.v20.services.ProductMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getPlannableTargetingFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
plannableProductCode_ = "";
plannableProductName_ = "";
plannableTargeting_ = null;
if (plannableTargetingBuilder_ != null) {
plannableTargetingBuilder_.dispose();
plannableTargetingBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ProductMetadata_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ProductMetadata getDefaultInstanceForType() {
return com.google.ads.googleads.v20.services.ProductMetadata.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ProductMetadata build() {
com.google.ads.googleads.v20.services.ProductMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ProductMetadata buildPartial() {
com.google.ads.googleads.v20.services.ProductMetadata result = new com.google.ads.googleads.v20.services.ProductMetadata(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.services.ProductMetadata result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.plannableProductCode_ = plannableProductCode_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.plannableProductName_ = plannableProductName_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.plannableTargeting_ = plannableTargetingBuilder_ == null
? plannableTargeting_
: plannableTargetingBuilder_.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.ads.googleads.v20.services.ProductMetadata) {
return mergeFrom((com.google.ads.googleads.v20.services.ProductMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.services.ProductMetadata other) {
if (other == com.google.ads.googleads.v20.services.ProductMetadata.getDefaultInstance()) return this;
if (other.hasPlannableProductCode()) {
plannableProductCode_ = other.plannableProductCode_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getPlannableProductName().isEmpty()) {
plannableProductName_ = other.plannableProductName_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasPlannableTargeting()) {
mergePlannableTargeting(other.getPlannableTargeting());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 18: {
input.readMessage(
getPlannableTargetingFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 18
case 26: {
plannableProductName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 26
case 34: {
plannableProductCode_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 34
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object plannableProductCode_ = "";
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return Whether the plannableProductCode field is set.
*/
public boolean hasPlannableProductCode() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The plannableProductCode.
*/
public java.lang.String getPlannableProductCode() {
java.lang.Object ref = plannableProductCode_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductCode_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return The bytes for plannableProductCode.
*/
public com.google.protobuf.ByteString
getPlannableProductCodeBytes() {
java.lang.Object ref = plannableProductCode_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductCode_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @param value The plannableProductCode to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductCode(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
plannableProductCode_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @return This builder for chaining.
*/
public Builder clearPlannableProductCode() {
plannableProductCode_ = getDefaultInstance().getPlannableProductCode();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The code associated with the ad product (for example: BUMPER,
* TRUEVIEW_IN_STREAM).
* To list the available plannable product codes use
* [ReachPlanService.ListPlannableProducts][google.ads.googleads.v20.services.ReachPlanService.ListPlannableProducts].
* </pre>
*
* <code>optional string plannable_product_code = 4;</code>
* @param value The bytes for plannableProductCode to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductCodeBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
plannableProductCode_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object plannableProductName_ = "";
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The plannableProductName.
*/
public java.lang.String getPlannableProductName() {
java.lang.Object ref = plannableProductName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
plannableProductName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return The bytes for plannableProductName.
*/
public com.google.protobuf.ByteString
getPlannableProductNameBytes() {
java.lang.Object ref = plannableProductName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
plannableProductName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @param value The plannableProductName to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
plannableProductName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPlannableProductName() {
plannableProductName_ = getDefaultInstance().getPlannableProductName();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* The name associated with the ad product.
* </pre>
*
* <code>string plannable_product_name = 3;</code>
* @param value The bytes for plannableProductName to set.
* @return This builder for chaining.
*/
public Builder setPlannableProductNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
plannableProductName_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.ads.googleads.v20.services.PlannableTargeting plannableTargeting_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.PlannableTargeting, com.google.ads.googleads.v20.services.PlannableTargeting.Builder, com.google.ads.googleads.v20.services.PlannableTargetingOrBuilder> plannableTargetingBuilder_;
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
* @return Whether the plannableTargeting field is set.
*/
public boolean hasPlannableTargeting() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
* @return The plannableTargeting.
*/
public com.google.ads.googleads.v20.services.PlannableTargeting getPlannableTargeting() {
if (plannableTargetingBuilder_ == null) {
return plannableTargeting_ == null ? com.google.ads.googleads.v20.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
} else {
return plannableTargetingBuilder_.getMessage();
}
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder setPlannableTargeting(com.google.ads.googleads.v20.services.PlannableTargeting value) {
if (plannableTargetingBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
plannableTargeting_ = value;
} else {
plannableTargetingBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder setPlannableTargeting(
com.google.ads.googleads.v20.services.PlannableTargeting.Builder builderForValue) {
if (plannableTargetingBuilder_ == null) {
plannableTargeting_ = builderForValue.build();
} else {
plannableTargetingBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder mergePlannableTargeting(com.google.ads.googleads.v20.services.PlannableTargeting value) {
if (plannableTargetingBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0) &&
plannableTargeting_ != null &&
plannableTargeting_ != com.google.ads.googleads.v20.services.PlannableTargeting.getDefaultInstance()) {
getPlannableTargetingBuilder().mergeFrom(value);
} else {
plannableTargeting_ = value;
}
} else {
plannableTargetingBuilder_.mergeFrom(value);
}
if (plannableTargeting_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public Builder clearPlannableTargeting() {
bitField0_ = (bitField0_ & ~0x00000004);
plannableTargeting_ = null;
if (plannableTargetingBuilder_ != null) {
plannableTargetingBuilder_.dispose();
plannableTargetingBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public com.google.ads.googleads.v20.services.PlannableTargeting.Builder getPlannableTargetingBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getPlannableTargetingFieldBuilder().getBuilder();
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
public com.google.ads.googleads.v20.services.PlannableTargetingOrBuilder getPlannableTargetingOrBuilder() {
if (plannableTargetingBuilder_ != null) {
return plannableTargetingBuilder_.getMessageOrBuilder();
} else {
return plannableTargeting_ == null ?
com.google.ads.googleads.v20.services.PlannableTargeting.getDefaultInstance() : plannableTargeting_;
}
}
/**
* <pre>
* The allowed plannable targeting for this product.
* </pre>
*
* <code>.google.ads.googleads.v20.services.PlannableTargeting plannable_targeting = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.PlannableTargeting, com.google.ads.googleads.v20.services.PlannableTargeting.Builder, com.google.ads.googleads.v20.services.PlannableTargetingOrBuilder>
getPlannableTargetingFieldBuilder() {
if (plannableTargetingBuilder_ == null) {
plannableTargetingBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.PlannableTargeting, com.google.ads.googleads.v20.services.PlannableTargeting.Builder, com.google.ads.googleads.v20.services.PlannableTargetingOrBuilder>(
getPlannableTargeting(),
getParentForChildren(),
isClean());
plannableTargeting_ = null;
}
return plannableTargetingBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.services.ProductMetadata)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.ProductMetadata)
private static final com.google.ads.googleads.v20.services.ProductMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.ProductMetadata();
}
public static com.google.ads.googleads.v20.services.ProductMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ProductMetadata>
PARSER = new com.google.protobuf.AbstractParser<ProductMetadata>() {
@java.lang.Override
public ProductMetadata 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<ProductMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ProductMetadata> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ProductMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.