repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
googleapis/sdk-platform-java
35,304
java-showcase/proto-gapic-showcase-v1beta1/src/main/java/com/google/showcase/v1beta1/ListBlurbsResponse.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: schema/google/showcase/v1beta1/messaging.proto // Protobuf Java Version: 3.25.8 package com.google.showcase.v1beta1; /** * * * <pre> * The response message for the google.showcase.v1beta1.Messaging&#92;ListBlurbs * method. * </pre> * * Protobuf type {@code google.showcase.v1beta1.ListBlurbsResponse} */ public final class ListBlurbsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.showcase.v1beta1.ListBlurbsResponse) ListBlurbsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListBlurbsResponse.newBuilder() to construct. private ListBlurbsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListBlurbsResponse() { blurbs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListBlurbsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.MessagingOuterClass .internal_static_google_showcase_v1beta1_ListBlurbsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.MessagingOuterClass .internal_static_google_showcase_v1beta1_ListBlurbsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.ListBlurbsResponse.class, com.google.showcase.v1beta1.ListBlurbsResponse.Builder.class); } public static final int BLURBS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.showcase.v1beta1.Blurb> blurbs_; /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ @java.lang.Override public java.util.List<com.google.showcase.v1beta1.Blurb> getBlurbsList() { return blurbs_; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.showcase.v1beta1.BlurbOrBuilder> getBlurbsOrBuilderList() { return blurbs_; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ @java.lang.Override public int getBlurbsCount() { return blurbs_.size(); } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ @java.lang.Override public com.google.showcase.v1beta1.Blurb getBlurbs(int index) { return blurbs_.get(index); } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ @java.lang.Override public com.google.showcase.v1beta1.BlurbOrBuilder getBlurbsOrBuilder(int index) { return blurbs_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < blurbs_.size(); i++) { output.writeMessage(1, blurbs_.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 < blurbs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, blurbs_.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.showcase.v1beta1.ListBlurbsResponse)) { return super.equals(obj); } com.google.showcase.v1beta1.ListBlurbsResponse other = (com.google.showcase.v1beta1.ListBlurbsResponse) obj; if (!getBlurbsList().equals(other.getBlurbsList())) 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 (getBlurbsCount() > 0) { hash = (37 * hash) + BLURBS_FIELD_NUMBER; hash = (53 * hash) + getBlurbsList().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.showcase.v1beta1.ListBlurbsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ListBlurbsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.showcase.v1beta1.ListBlurbsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ListBlurbsResponse 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.showcase.v1beta1.ListBlurbsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.ListBlurbsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.showcase.v1beta1.ListBlurbsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ListBlurbsResponse 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.showcase.v1beta1.ListBlurbsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ListBlurbsResponse 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.showcase.v1beta1.ListBlurbsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.ListBlurbsResponse 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.showcase.v1beta1.ListBlurbsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response message for the google.showcase.v1beta1.Messaging&#92;ListBlurbs * method. * </pre> * * Protobuf type {@code google.showcase.v1beta1.ListBlurbsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.showcase.v1beta1.ListBlurbsResponse) com.google.showcase.v1beta1.ListBlurbsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.MessagingOuterClass .internal_static_google_showcase_v1beta1_ListBlurbsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.MessagingOuterClass .internal_static_google_showcase_v1beta1_ListBlurbsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.ListBlurbsResponse.class, com.google.showcase.v1beta1.ListBlurbsResponse.Builder.class); } // Construct using com.google.showcase.v1beta1.ListBlurbsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (blurbsBuilder_ == null) { blurbs_ = java.util.Collections.emptyList(); } else { blurbs_ = null; blurbsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.showcase.v1beta1.MessagingOuterClass .internal_static_google_showcase_v1beta1_ListBlurbsResponse_descriptor; } @java.lang.Override public com.google.showcase.v1beta1.ListBlurbsResponse getDefaultInstanceForType() { return com.google.showcase.v1beta1.ListBlurbsResponse.getDefaultInstance(); } @java.lang.Override public com.google.showcase.v1beta1.ListBlurbsResponse build() { com.google.showcase.v1beta1.ListBlurbsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.showcase.v1beta1.ListBlurbsResponse buildPartial() { com.google.showcase.v1beta1.ListBlurbsResponse result = new com.google.showcase.v1beta1.ListBlurbsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.showcase.v1beta1.ListBlurbsResponse result) { if (blurbsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { blurbs_ = java.util.Collections.unmodifiableList(blurbs_); bitField0_ = (bitField0_ & ~0x00000001); } result.blurbs_ = blurbs_; } else { result.blurbs_ = blurbsBuilder_.build(); } } private void buildPartial0(com.google.showcase.v1beta1.ListBlurbsResponse 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.showcase.v1beta1.ListBlurbsResponse) { return mergeFrom((com.google.showcase.v1beta1.ListBlurbsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.showcase.v1beta1.ListBlurbsResponse other) { if (other == com.google.showcase.v1beta1.ListBlurbsResponse.getDefaultInstance()) return this; if (blurbsBuilder_ == null) { if (!other.blurbs_.isEmpty()) { if (blurbs_.isEmpty()) { blurbs_ = other.blurbs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureBlurbsIsMutable(); blurbs_.addAll(other.blurbs_); } onChanged(); } } else { if (!other.blurbs_.isEmpty()) { if (blurbsBuilder_.isEmpty()) { blurbsBuilder_.dispose(); blurbsBuilder_ = null; blurbs_ = other.blurbs_; bitField0_ = (bitField0_ & ~0x00000001); blurbsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getBlurbsFieldBuilder() : null; } else { blurbsBuilder_.addAllMessages(other.blurbs_); } } } 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.showcase.v1beta1.Blurb m = input.readMessage( com.google.showcase.v1beta1.Blurb.parser(), extensionRegistry); if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); blurbs_.add(m); } else { blurbsBuilder_.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.showcase.v1beta1.Blurb> blurbs_ = java.util.Collections.emptyList(); private void ensureBlurbsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { blurbs_ = new java.util.ArrayList<com.google.showcase.v1beta1.Blurb>(blurbs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.Blurb, com.google.showcase.v1beta1.Blurb.Builder, com.google.showcase.v1beta1.BlurbOrBuilder> blurbsBuilder_; /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public java.util.List<com.google.showcase.v1beta1.Blurb> getBlurbsList() { if (blurbsBuilder_ == null) { return java.util.Collections.unmodifiableList(blurbs_); } else { return blurbsBuilder_.getMessageList(); } } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public int getBlurbsCount() { if (blurbsBuilder_ == null) { return blurbs_.size(); } else { return blurbsBuilder_.getCount(); } } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public com.google.showcase.v1beta1.Blurb getBlurbs(int index) { if (blurbsBuilder_ == null) { return blurbs_.get(index); } else { return blurbsBuilder_.getMessage(index); } } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder setBlurbs(int index, com.google.showcase.v1beta1.Blurb value) { if (blurbsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlurbsIsMutable(); blurbs_.set(index, value); onChanged(); } else { blurbsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder setBlurbs(int index, com.google.showcase.v1beta1.Blurb.Builder builderForValue) { if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); blurbs_.set(index, builderForValue.build()); onChanged(); } else { blurbsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder addBlurbs(com.google.showcase.v1beta1.Blurb value) { if (blurbsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlurbsIsMutable(); blurbs_.add(value); onChanged(); } else { blurbsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder addBlurbs(int index, com.google.showcase.v1beta1.Blurb value) { if (blurbsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBlurbsIsMutable(); blurbs_.add(index, value); onChanged(); } else { blurbsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder addBlurbs(com.google.showcase.v1beta1.Blurb.Builder builderForValue) { if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); blurbs_.add(builderForValue.build()); onChanged(); } else { blurbsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder addBlurbs(int index, com.google.showcase.v1beta1.Blurb.Builder builderForValue) { if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); blurbs_.add(index, builderForValue.build()); onChanged(); } else { blurbsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder addAllBlurbs( java.lang.Iterable<? extends com.google.showcase.v1beta1.Blurb> values) { if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, blurbs_); onChanged(); } else { blurbsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder clearBlurbs() { if (blurbsBuilder_ == null) { blurbs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { blurbsBuilder_.clear(); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public Builder removeBlurbs(int index) { if (blurbsBuilder_ == null) { ensureBlurbsIsMutable(); blurbs_.remove(index); onChanged(); } else { blurbsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public com.google.showcase.v1beta1.Blurb.Builder getBlurbsBuilder(int index) { return getBlurbsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public com.google.showcase.v1beta1.BlurbOrBuilder getBlurbsOrBuilder(int index) { if (blurbsBuilder_ == null) { return blurbs_.get(index); } else { return blurbsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public java.util.List<? extends com.google.showcase.v1beta1.BlurbOrBuilder> getBlurbsOrBuilderList() { if (blurbsBuilder_ != null) { return blurbsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(blurbs_); } } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public com.google.showcase.v1beta1.Blurb.Builder addBlurbsBuilder() { return getBlurbsFieldBuilder() .addBuilder(com.google.showcase.v1beta1.Blurb.getDefaultInstance()); } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public com.google.showcase.v1beta1.Blurb.Builder addBlurbsBuilder(int index) { return getBlurbsFieldBuilder() .addBuilder(index, com.google.showcase.v1beta1.Blurb.getDefaultInstance()); } /** * * * <pre> * The list of blurbs. * </pre> * * <code>repeated .google.showcase.v1beta1.Blurb blurbs = 1;</code> */ public java.util.List<com.google.showcase.v1beta1.Blurb.Builder> getBlurbsBuilderList() { return getBlurbsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.Blurb, com.google.showcase.v1beta1.Blurb.Builder, com.google.showcase.v1beta1.BlurbOrBuilder> getBlurbsFieldBuilder() { if (blurbsBuilder_ == null) { blurbsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.showcase.v1beta1.Blurb, com.google.showcase.v1beta1.Blurb.Builder, com.google.showcase.v1beta1.BlurbOrBuilder>( blurbs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); blurbs_ = null; } return blurbsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass this value in ListBlurbsRequest.page_token field in the subsequent * call to `google.showcase.v1beta1.Blurb&#92;ListBlurbs` method to retrieve * the next page of results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.showcase.v1beta1.ListBlurbsResponse) } // @@protoc_insertion_point(class_scope:google.showcase.v1beta1.ListBlurbsResponse) private static final com.google.showcase.v1beta1.ListBlurbsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.showcase.v1beta1.ListBlurbsResponse(); } public static com.google.showcase.v1beta1.ListBlurbsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListBlurbsResponse> PARSER = new com.google.protobuf.AbstractParser<ListBlurbsResponse>() { @java.lang.Override public ListBlurbsResponse 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<ListBlurbsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListBlurbsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.showcase.v1beta1.ListBlurbsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/syncope
35,663
core/provisioning-java/src/main/java/org/apache/syncope/core/provisioning/java/propagation/DefaultPropagationManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.provisioning.java.propagation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.syncope.common.lib.request.AnyUR; import org.apache.syncope.common.lib.request.LinkedAccountUR; import org.apache.syncope.common.lib.request.PasswordPatch; import org.apache.syncope.common.lib.request.UserUR; import org.apache.syncope.common.lib.to.Item; import org.apache.syncope.common.lib.to.LinkedAccountTO; import org.apache.syncope.common.lib.to.OrgUnit; import org.apache.syncope.common.lib.to.Provision; import org.apache.syncope.common.lib.types.AnyTypeKind; import org.apache.syncope.common.lib.types.PatchOperation; import org.apache.syncope.common.lib.types.ResourceOperation; import org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO; import org.apache.syncope.core.persistence.api.dao.NotFoundException; import org.apache.syncope.core.persistence.api.entity.Any; import org.apache.syncope.core.persistence.api.entity.AnyUtilsFactory; import org.apache.syncope.core.persistence.api.entity.EntityFactory; import org.apache.syncope.core.persistence.api.entity.ExternalResource; import org.apache.syncope.core.persistence.api.entity.Realm; import org.apache.syncope.core.persistence.api.entity.policy.PropagationPolicy; import org.apache.syncope.core.persistence.api.entity.task.PropagationData; import org.apache.syncope.core.persistence.api.entity.user.LinkedAccount; import org.apache.syncope.core.persistence.api.entity.user.User; import org.apache.syncope.core.provisioning.api.DerAttrHandler; import org.apache.syncope.core.provisioning.api.MappingManager; import org.apache.syncope.core.provisioning.api.PropagationByResource; import org.apache.syncope.core.provisioning.api.UserWorkflowResult; import org.apache.syncope.core.provisioning.api.jexl.JexlUtils; import org.apache.syncope.core.provisioning.api.propagation.PropagationManager; import org.apache.syncope.core.provisioning.api.propagation.PropagationTaskInfo; import org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils; import org.apache.syncope.core.provisioning.java.utils.MappingUtils; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeBuilder; import org.identityconnectors.framework.common.objects.AttributeDelta; import org.identityconnectors.framework.common.objects.AttributeDeltaBuilder; import org.identityconnectors.framework.common.objects.AttributeUtil; import org.identityconnectors.framework.common.objects.Name; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; /** * Manage the data propagation to external resources. */ @Transactional(rollbackFor = { Throwable.class }) public class DefaultPropagationManager implements PropagationManager { protected static final Logger LOG = LoggerFactory.getLogger(PropagationManager.class); protected final ExternalResourceDAO resourceDAO; protected final EntityFactory entityFactory; protected final ConnObjectUtils connObjectUtils; protected final MappingManager mappingManager; protected final DerAttrHandler derAttrHandler; protected final AnyUtilsFactory anyUtilsFactory; public DefaultPropagationManager( final ExternalResourceDAO resourceDAO, final EntityFactory entityFactory, final ConnObjectUtils connObjectUtils, final MappingManager mappingManager, final DerAttrHandler derAttrHandler, final AnyUtilsFactory anyUtilsFactory) { this.resourceDAO = resourceDAO; this.entityFactory = entityFactory; this.connObjectUtils = connObjectUtils; this.mappingManager = mappingManager; this.derAttrHandler = derAttrHandler; this.anyUtilsFactory = anyUtilsFactory; } @Override public List<PropagationTaskInfo> getCreateTasks( final AnyTypeKind kind, final String key, final Boolean enable, final PropagationByResource<String> propByRes, final Collection<String> excludedResources) { return getCreateTasks( anyUtilsFactory.getInstance(kind).dao().authFind(key), null, enable, propByRes, null, excludedResources); } @Override public List<PropagationTaskInfo> getUserCreateTasks( final String key, final String password, final Boolean enable, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { return getCreateTasks( anyUtilsFactory.getInstance(AnyTypeKind.USER).dao().authFind(key), password, enable, propByRes, propByLinkedAccount, excludedResources); } protected List<PropagationTaskInfo> getCreateTasks( final Any any, final String password, final Boolean enable, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { if ((propByRes == null || propByRes.isEmpty()) && (propByLinkedAccount == null || propByLinkedAccount.isEmpty())) { return List.of(); } List<String> changePwdRes = new ArrayList<>(); if (excludedResources != null) { if (propByRes != null) { propByRes.get(ResourceOperation.CREATE).removeAll(excludedResources); } if (propByLinkedAccount != null) { propByLinkedAccount.get(ResourceOperation.CREATE). removeIf(account -> excludedResources.contains(account.getLeft())); } } if (propByRes != null) { propByRes.asMap().forEach((resource, resourceOperation) -> changePwdRes.add(resource)); } if (propByLinkedAccount != null) { propByLinkedAccount.asMap().forEach((resource, resourceOperation) -> changePwdRes.add(resource.getKey())); } return createTasks(any, password, changePwdRes, enable, propByRes, propByLinkedAccount); } @Override public List<PropagationTaskInfo> getUpdateTasks( final AnyUR anyUR, final AnyTypeKind kind, final String key, final List<String> changePwdRes, final Boolean enable, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { return getUpdateTasks( anyUR, anyUtilsFactory.getInstance(kind).dao().authFind(key), null, changePwdRes, enable, propByRes, propByLinkedAccount, excludedResources); } @Override public List<PropagationTaskInfo> getUserUpdateTasks( final UserWorkflowResult<Pair<UserUR, Boolean>> wfResult, final List<String> changePwdRes, final Collection<String> excludedResources) { return getUpdateTasks( wfResult.getResult().getLeft(), anyUtilsFactory.getInstance(AnyTypeKind.USER).dao().authFind(wfResult.getResult().getLeft().getKey()), Optional.ofNullable(wfResult.getResult().getLeft().getPassword()). map(PasswordPatch::getValue).orElse(null), changePwdRes, wfResult.getResult().getRight(), wfResult.getPropByRes(), wfResult.getPropByLinkedAccount(), excludedResources); } @Override public List<PropagationTaskInfo> getUserUpdateTasks(final UserWorkflowResult<Pair<UserUR, Boolean>> wfResult) { UserUR userUR = wfResult.getResult().getLeft(); List<String> urPwdResources = userUR.getPassword() == null ? List.of() : userUR.getPassword().getResources().stream().distinct().toList(); List<String> laPwdResources = userUR.getLinkedAccounts().stream(). filter(laur -> laur.getOperation() == PatchOperation.ADD_REPLACE). map(LinkedAccountUR::getLinkedAccountTO). filter(la -> la != null && la.getPassword() != null). map(LinkedAccountTO::getResource). distinct().toList(); List<String> pwdResources = Stream.concat(urPwdResources.stream(), laPwdResources.stream()). distinct().toList(); // Propagate password update only to requested resources List<PropagationTaskInfo> tasks; if (pwdResources.isEmpty()) { // a. no specific password propagation request: generate propagation tasks for any resource associated tasks = getUserUpdateTasks(wfResult, List.of(), null); } else { // b. generate the propagation task list in two phases: first the ones with no password, then the others tasks = new ArrayList<>(); PropagationByResource<String> urNoPwdPropByRes = new PropagationByResource<>(); urNoPwdPropByRes.merge(wfResult.getPropByRes()); urNoPwdPropByRes.purge(); urNoPwdPropByRes.removeAll(urPwdResources); PropagationByResource<Pair<String, String>> laNoPwdPropByRes = new PropagationByResource<>(); laNoPwdPropByRes.merge(wfResult.getPropByLinkedAccount()); laNoPwdPropByRes.purge(); laNoPwdPropByRes.removeIf(p -> laPwdResources.contains(p.getLeft())); if (!urNoPwdPropByRes.isEmpty() || !laNoPwdPropByRes.isEmpty()) { UserWorkflowResult<Pair<UserUR, Boolean>> noPwdWFResult = new UserWorkflowResult<>( wfResult.getResult(), urNoPwdPropByRes, laNoPwdPropByRes, wfResult.getPerformedTasks()); tasks.addAll(getUserUpdateTasks(noPwdWFResult, List.of(), null)); } PropagationByResource<String> urPwdPropByRes = new PropagationByResource<>(); urPwdPropByRes.merge(wfResult.getPropByRes()); urPwdPropByRes.purge(); urPwdPropByRes.retainAll(urPwdResources); PropagationByResource<Pair<String, String>> laPwdPropByRes = new PropagationByResource<>(); laPwdPropByRes.merge(wfResult.getPropByLinkedAccount()); laPwdPropByRes.purge(); laPwdPropByRes.removeIf(p -> !laPwdResources.contains(p.getLeft())); if (!urPwdPropByRes.isEmpty() || !laPwdPropByRes.isEmpty()) { UserWorkflowResult<Pair<UserUR, Boolean>> pwdWFResult = new UserWorkflowResult<>( wfResult.getResult(), urPwdPropByRes, laPwdPropByRes, wfResult.getPerformedTasks()); tasks.addAll(getUserUpdateTasks(pwdWFResult, pwdResources, null)); } } return tasks; } protected List<PropagationTaskInfo> getUpdateTasks( final AnyUR anyUR, final Any any, final String password, final List<String> changePwdRes, final Boolean enable, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { if (excludedResources != null) { if (propByRes != null) { propByRes.removeAll(excludedResources); } if (propByLinkedAccount != null) { propByLinkedAccount.get(ResourceOperation.CREATE). removeIf(account -> excludedResources.contains(account.getLeft())); propByLinkedAccount.get(ResourceOperation.UPDATE). removeIf(account -> excludedResources.contains(account.getLeft())); propByLinkedAccount.get(ResourceOperation.DELETE). removeIf(account -> excludedResources.contains(account.getLeft())); } } List<PropagationTaskInfo> tasks = createTasks( any, password, changePwdRes, enable, Optional.ofNullable(propByRes).orElseGet(PropagationByResource::new), propByLinkedAccount); tasks.forEach(task -> task.setUpdateRequest(anyUR)); return tasks; } @Override public List<PropagationTaskInfo> getDeleteTasks( final AnyTypeKind kind, final String key, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { return getDeleteTasks( anyUtilsFactory.getInstance(kind).dao().authFind(key), propByRes, propByLinkedAccount, excludedResources); } protected List<PropagationTaskInfo> getDeleteTasks( final Any any, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount, final Collection<String> excludedResources) { PropagationByResource<String> localPropByRes = new PropagationByResource<>(); if (propByRes == null || propByRes.isEmpty()) { localPropByRes.addAll( ResourceOperation.DELETE, anyUtilsFactory.getInstance(any).dao().findAllResourceKeys(any.getKey())); } else { localPropByRes.merge(propByRes); } if (excludedResources != null) { localPropByRes.removeAll(excludedResources); if (propByLinkedAccount != null) { propByLinkedAccount.get(ResourceOperation.CREATE). removeIf(account -> excludedResources.contains(account.getLeft())); propByLinkedAccount.get(ResourceOperation.UPDATE). removeIf(account -> excludedResources.contains(account.getLeft())); propByLinkedAccount.get(ResourceOperation.DELETE). removeIf(account -> excludedResources.contains(account.getLeft())); } } return createTasks(any, null, List.of(), false, localPropByRes, propByLinkedAccount); } @Override public PropagationTaskInfo newTask( final DerAttrHandler derAttrHandler, final Any any, final ExternalResource resource, final ResourceOperation operation, final Provision provision, final Stream<Item> mappingItems, final Pair<String, Set<Attribute>> preparedAttrs) { // Check if any of mandatory attributes (in the mapping) is missing or not received any value: // if so, add special attributes that will be evaluated by PropagationTaskExecutor List<String> mandatoryMissing = new ArrayList<>(); List<String> mandatoryNullOrEmpty = new ArrayList<>(); mappingItems.filter(item -> !item.isConnObjectKey() && JexlUtils.evaluateMandatoryCondition(item.getMandatoryCondition(), any, derAttrHandler)). forEach(item -> { Attribute attr = AttributeUtil.find(item.getExtAttrName(), preparedAttrs.getRight()); if (attr == null) { mandatoryMissing.add(item.getExtAttrName()); } else if (CollectionUtils.isEmpty(attr.getValue())) { mandatoryNullOrEmpty.add(item.getExtAttrName()); } }); if (!mandatoryMissing.isEmpty()) { preparedAttrs.getRight().add(AttributeBuilder.build( MANDATORY_MISSING_ATTR_NAME, mandatoryMissing)); } if (!mandatoryNullOrEmpty.isEmpty()) { preparedAttrs.getRight().add(AttributeBuilder.build( MANDATORY_NULL_OR_EMPTY_ATTR_NAME, mandatoryNullOrEmpty)); } return new PropagationTaskInfo( resource, operation, new ObjectClass(provision.getObjectClass()), any.getType().getKind(), any.getType().getKey(), any.getKey(), preparedAttrs.getLeft(), new PropagationData(preparedAttrs.getRight())); } /** * Create propagation tasks. * * @param any to be provisioned * @param password clear text password to be provisioned * @param changePwdRes the resources in which the password must be included in the propagation attributes * @param enable whether user must be enabled or not * @param propByRes operation to be performed per resource * @param propByLinkedAccount operation to be performed on linked accounts * @return list of propagation tasks created */ protected List<PropagationTaskInfo> createTasks( final Any any, final String password, final List<String> changePwdRes, final Boolean enable, final PropagationByResource<String> propByRes, final PropagationByResource<Pair<String, String>> propByLinkedAccount) { LOG.debug("Provisioning {}:\n{}", any, propByRes); // Avoid duplicates - see javadoc propByRes.purge(); LOG.debug("After purge {}:\n{}", any, propByRes); List<PropagationTaskInfo> tasks = new ArrayList<>(); propByRes.asMap().forEach((resourceKey, operation) -> { ExternalResource resource = resourceDAO.findById(resourceKey).orElse(null); Provision provision = Optional.ofNullable(resource). flatMap(r -> r.getProvisionByAnyType(any.getType().getKey())).orElse(null); Stream<Item> mappingItems = provision == null ? Stream.empty() : MappingUtils.getPropagationItems(provision.getMapping().getItems().stream()); if (resource == null) { LOG.error("Invalid resource name specified: {}, ignoring...", resourceKey); } else if (provision == null) { LOG.error("No provision specified on resource {} for type {}, ignoring...", resource, any.getType()); } else if (provision.getMapping() == null || provision.getMapping().getItems().isEmpty()) { LOG.warn("Requesting propagation for {} but no propagation mapping provided for {}", any.getType(), resource); } else { Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrsFromAny(any, password, changePwdRes.contains(resourceKey), enable, resource, provision); PropagationTaskInfo task = newTask( derAttrHandler, any, resource, operation, provision, mappingItems, preparedAttrs); task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resourceKey)); tasks.add(task); LOG.debug("PropagationTask created: {}", task); } }); if (any instanceof final User user && propByLinkedAccount != null) { propByLinkedAccount.asMap().forEach((accountInfo, operation) -> { LinkedAccount account = user.getLinkedAccount(accountInfo.getLeft(), accountInfo.getRight()). orElse(null); if (account == null && operation == ResourceOperation.DELETE) { account = new DeletingLinkedAccount( user, resourceDAO.findById(accountInfo.getLeft()). orElseThrow(() -> new NotFoundException("Resource " + accountInfo.getLeft())), accountInfo.getRight()); } Provision provision = account == null || account.getResource() == null ? null : account.getResource().getProvisionByAnyType(AnyTypeKind.USER.name()).orElse(null); Stream<Item> mappingItems = provision == null ? Stream.empty() : MappingUtils.getPropagationItems(provision.getMapping().getItems().stream()); if (account == null) { LOG.error("Invalid operation {} on deleted account {} on resource {}, ignoring...", operation, accountInfo.getRight(), accountInfo.getLeft()); } else if (account.getResource() == null) { LOG.error("Invalid resource name specified: {}, ignoring...", accountInfo.getLeft()); } else if (provision == null) { LOG.error("No provision specified on resource {} for type {}, ignoring...", account.getResource(), AnyTypeKind.USER.name()); } else if (provision.getMapping() == null || provision.getMapping().getItems().isEmpty()) { LOG.warn("Requesting propagation for {} but no propagation mapping provided for {}", AnyTypeKind.USER.name(), account.getResource()); } else { PropagationTaskInfo accountTask = newTask( derAttrHandler, user, account.getResource(), operation, provision, mappingItems, Pair.of(account.getConnObjectKeyValue(), mappingManager.prepareAttrsFromLinkedAccount( user, account, password, changePwdRes.contains(account.getResource().getKey()), provision))); tasks.add(accountTask); LOG.debug("PropagationTask created for Linked Account {}: {}", account.getConnObjectKeyValue(), accountTask); } }); } return tasks; } @Override public List<PropagationTaskInfo> createTasks( final Realm realm, final PropagationByResource<String> propByRes, final Collection<String> excludedResources) { if (excludedResources != null) { propByRes.removeAll(excludedResources); } LOG.debug("Provisioning {}:\n{}", realm, propByRes); // Avoid duplicates - see javadoc propByRes.purge(); LOG.debug("After purge {}:\n{}", realm, propByRes); List<PropagationTaskInfo> tasks = new ArrayList<>(); propByRes.asMap().forEach((resourceKey, operation) -> { ExternalResource resource = resourceDAO.findById(resourceKey). orElseThrow(() -> new NotFoundException("Resource " + resourceKey)); OrgUnit orgUnit = Optional.ofNullable(resource).map(ExternalResource::getOrgUnit).orElse(null); if (resource == null) { LOG.error("Invalid resource name specified: {}, ignoring...", resourceKey); } else if (orgUnit == null) { LOG.error("No orgUnit specified on resource {}, ignoring...", resource); } else if (StringUtils.isBlank(orgUnit.getConnObjectLink())) { LOG.warn("Requesting propagation for {} but no ConnObjectLink provided for {}", realm.getFullPath(), resource); } else { Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrsFromRealm(realm, resource); PropagationTaskInfo task = new PropagationTaskInfo( resource, operation, new ObjectClass(orgUnit.getObjectClass()), null, null, realm.getKey(), preparedAttrs.getLeft(), new PropagationData(preparedAttrs.getRight())); task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey())); tasks.add(task); LOG.debug("PropagationTask created: {}", task); } }); return tasks; } @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) @Override public Map<Pair<String, String>, Set<Attribute>> prepareAttrs( final AnyTypeKind kind, final String key, final String password, final List<String> changePwdRes, final Boolean enable, final Collection<String> excludedResources) { Map<Pair<String, String>, Set<Attribute>> attrs = new HashMap<>(); Any any = anyUtilsFactory.getInstance(kind).dao().authFind(key); anyUtilsFactory.getInstance(kind).dao().findAllResourceKeys(key).stream(). filter(Predicate.not(excludedResources::contains)). map(resourceDAO::findById). flatMap(Optional::stream). filter(resource -> Optional.ofNullable(resource.getPropagationPolicy()). map(PropagationPolicy::isUpdateDelta).orElse(false)). forEach(resource -> resource.getProvisionByAnyType(any.getType().getKey()). ifPresent(provision -> { Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrsFromAny( any, password, changePwdRes.contains(resource.getKey()), enable, resource, provision); attrs.put( Pair.of(resource.getKey(), preparedAttrs.getLeft()), preparedAttrs.getRight()); })); if (any instanceof User user) { user.getLinkedAccounts().stream(). filter(account -> !excludedResources.contains(account.getResource().getKey()) && account.getResource().getProvisionByAnyType(user.getType().getKey()).isPresent() && Optional.ofNullable(account.getResource().getPropagationPolicy()). map(PropagationPolicy::isUpdateDelta).orElse(false)). forEach(account -> account.getResource().getProvisionByAnyType(user.getType().getKey()). ifPresent(provision -> { Set<Attribute> preparedAttrs = mappingManager.prepareAttrsFromLinkedAccount( user, account, password, true, provision); attrs.put( Pair.of(account.getResource().getKey(), account.getConnObjectKeyValue()), preparedAttrs); })); } LOG.debug("Prepared attrs for {} {}: {}", kind, key, attrs); return attrs; } @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) @Override public Map<Pair<String, String>, Set<Attribute>> prepareAttrs(final Realm realm) { Map<Pair<String, String>, Set<Attribute>> attrs = new HashMap<>(); realm.getResources().stream(). filter(resource -> resource.getOrgUnit() != null && Optional.ofNullable(resource.getPropagationPolicy()). map(PropagationPolicy::isUpdateDelta).orElse(false)). forEach(resource -> { Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrsFromRealm( realm, resource); attrs.put( Pair.of(resource.getKey(), preparedAttrs.getLeft()), preparedAttrs.getRight()); }); LOG.debug("Prepared attrs for Realm {}: {}", realm.getKey(), attrs); return attrs; } /** * Checks whether the given attribute shall be treated as an ordinary attribute or not, for purpose of building * AttributeDelta instances. * * @param attr ConnId attribute * @return whether the condition is matched or not */ protected boolean isOrdinaryForAttrForDelta(final Attribute attr) { return !attr.is(Name.NAME) && !OperationalAttributes.isOperationalAttribute(attr); } @Override public List<PropagationTaskInfo> setAttributeDeltas( final List<PropagationTaskInfo> tasks, final Map<Pair<String, String>, Set<Attribute>> beforeAttrs) { if (beforeAttrs.isEmpty()) { return tasks; } for (PropagationTaskInfo task : tasks) { // rename is not supported by updateDelta if (task.getOldConnObjectKey() != null && !task.getConnObjectKey().equals(task.getOldConnObjectKey())) { continue; } Pair<String, String> key = Pair.of(task.getResource().getKey(), task.getConnObjectKey()); if (!beforeAttrs.containsKey(key)) { continue; } Set<Attribute> attrs = new HashSet<>(beforeAttrs.get(key)); // purge unwanted attributes, even though prepared attrs.removeIf( attr -> MANDATORY_MISSING_ATTR_NAME.equals(attr.getName()) || MANDATORY_NULL_OR_EMPTY_ATTR_NAME.equals(attr.getName())); PropagationData propagationData = task.getPropagationData(); Set<AttributeDelta> attributeDeltas = new HashSet<>(); // build delta for updated attributes propagationData.getAttributes().forEach(next -> { Set<Object> valuesToAdd = new HashSet<>(); Set<Object> valuesToRemove = new HashSet<>(); Optional.ofNullable(AttributeUtil.find(next.getName(), attrs)).ifPresent(prev -> { // password is unchanged from beforeAttrs but needs to be taken into account anyway if (next.is(OperationalAttributes.PASSWORD_NAME)) { valuesToAdd.addAll(next.getValue()); } else { if (next.getValue() == null && prev.getValue() != null) { valuesToRemove.addAll(prev.getValue()); } else if (next.getValue() != null && prev.getValue() == null) { valuesToAdd.addAll(next.getValue()); } else if (next.getValue() != null && prev.getValue() != null) { next.getValue().stream(). filter(value -> !prev.getValue().contains(value)). forEach(valuesToAdd::add); prev.getValue().stream(). filter(value -> !next.getValue().contains(value)). forEach(valuesToRemove::add); } } }); // Following org.identityconnectors.framework.impl.api.local.operations.UpdateDeltaImpl#updateDelta // we create AttributeDelta instances with (valuesToAdd, valuesToRemove) or (valuesToReplace) // depending on the attribute name if (isOrdinaryForAttrForDelta(next)) { if (!valuesToAdd.isEmpty() || !valuesToRemove.isEmpty()) { attributeDeltas.add(AttributeDeltaBuilder.build(next.getName(), valuesToAdd, valuesToRemove)); } } else { if (!valuesToAdd.isEmpty()) { attributeDeltas.add(AttributeDeltaBuilder.build(next.getName(), valuesToAdd)); } } }); // build delta for new or removed attributes Set<String> nextNames = propagationData.getAttributes().stream(). filter(this::isOrdinaryForAttrForDelta). map(Attribute::getName). collect(Collectors.toSet()); Set<String> prevNames = attrs.stream(). filter(this::isOrdinaryForAttrForDelta). map(Attribute::getName). collect(Collectors.toSet()); nextNames.stream().filter(name -> !prevNames.contains(name)). forEach(toAdd -> Optional.ofNullable(AttributeUtil.find(toAdd, propagationData.getAttributes())). ifPresent(attr -> attributeDeltas.add( AttributeDeltaBuilder.build(attr.getName(), attr.getValue(), Set.of())))); prevNames.stream().filter(name -> !nextNames.contains(name)). forEach(toRemove -> Optional.ofNullable(AttributeUtil.find(toRemove, attrs)). ifPresent(attr -> attributeDeltas.add( AttributeDeltaBuilder.build(attr.getName(), Set.of(), attr.getValue())))); if (!attributeDeltas.isEmpty()) { propagationData.setAttributeDeltas(attributeDeltas); } } return tasks; } }
googleapis/google-api-java-client-services
35,334
clients/google-api-services-compute/v1/1.31.0/com/google/api/services/compute/model/Operation.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents an Operation resource. Google Compute Engine has three Operation resources: * * [Global](/compute/docs/reference/rest/v1/globalOperations) * * [Regional](/compute/docs/reference/rest/v1/regionOperations) * * [Zonal](/compute/docs/reference/rest/v1/zoneOperations) You can use an operation resource to * manage asynchronous API requests. For more information, read Handling API responses. Operations * can be global, regional or zonal. - For global operations, use the `globalOperations` resource. - * For regional operations, use the `regionOperations` resource. - For zonal operations, use the * `zonalOperations` resource. For more information, read Global, Regional, and Zonal Resources. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Operation extends com.google.api.client.json.GenericJson { /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String clientOperationId; /** * [Deprecated] This field is deprecated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String endTime; /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private Error error; /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String httpErrorMessage; /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer httpErrorStatusCode; /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String insertTime; /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * [Output Only] Name of the operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String operationGroupId; /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String operationType; /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer progress; /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String startTime; /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String status; /** * [Output Only] An optional textual description of the current status of the operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String statusMessage; /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger targetId; /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String targetLink; /** * [Output Only] User who requested the operation, for example: `user@example.com`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String user; /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Warnings> warnings; static { // hack to force ProGuard to consider Warnings 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(Warnings.class); } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String zone; /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @return value or {@code null} for none */ public java.lang.String getClientOperationId() { return clientOperationId; } /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @param clientOperationId clientOperationId or {@code null} for none */ public Operation setClientOperationId(java.lang.String clientOperationId) { this.clientOperationId = clientOperationId; return this; } /** * [Deprecated] This field is deprecated. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Deprecated] This field is deprecated. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Operation setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @param description description or {@code null} for none */ public Operation setDescription(java.lang.String description) { this.description = description; return this; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getEndTime() { return endTime; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @param endTime endTime or {@code null} for none */ public Operation setEndTime(java.lang.String endTime) { this.endTime = endTime; return this; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @return value or {@code null} for none */ public Error getError() { return error; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @param error error or {@code null} for none */ public Operation setError(Error error) { this.error = error; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * @return value or {@code null} for none */ public java.lang.String getHttpErrorMessage() { return httpErrorMessage; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * @param httpErrorMessage httpErrorMessage or {@code null} for none */ public Operation setHttpErrorMessage(java.lang.String httpErrorMessage) { this.httpErrorMessage = httpErrorMessage; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * @return value or {@code null} for none */ public java.lang.Integer getHttpErrorStatusCode() { return httpErrorStatusCode; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * @param httpErrorStatusCode httpErrorStatusCode or {@code null} for none */ public Operation setHttpErrorStatusCode(java.lang.Integer httpErrorStatusCode) { this.httpErrorStatusCode = httpErrorStatusCode; return this; } /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * @param id id or {@code null} for none */ public Operation setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getInsertTime() { return insertTime; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @param insertTime insertTime or {@code null} for none */ public Operation setInsertTime(java.lang.String insertTime) { this.insertTime = insertTime; return this; } /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * @param kind kind or {@code null} for none */ public Operation setKind(java.lang.String kind) { this.kind = kind; return this; } /** * [Output Only] Name of the operation. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * [Output Only] Name of the operation. * @param name name or {@code null} for none */ public Operation setName(java.lang.String name) { this.name = name; return this; } /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * @return value or {@code null} for none */ public java.lang.String getOperationGroupId() { return operationGroupId; } /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * @param operationGroupId operationGroupId or {@code null} for none */ public Operation setOperationGroupId(java.lang.String operationGroupId) { this.operationGroupId = operationGroupId; return this; } /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * @return value or {@code null} for none */ public java.lang.String getOperationType() { return operationType; } /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * @param operationType operationType or {@code null} for none */ public Operation setOperationType(java.lang.String operationType) { this.operationType = operationType; return this; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @return value or {@code null} for none */ public java.lang.Integer getProgress() { return progress; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @param progress progress or {@code null} for none */ public Operation setProgress(java.lang.Integer progress) { this.progress = progress; return this; } /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * @param region region or {@code null} for none */ public Operation setRegion(java.lang.String region) { this.region = region; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Operation setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @return value or {@code null} for none */ public java.lang.String getStartTime() { return startTime; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @param startTime startTime or {@code null} for none */ public Operation setStartTime(java.lang.String startTime) { this.startTime = startTime; return this; } /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * @return value or {@code null} for none */ public java.lang.String getStatus() { return status; } /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * @param status status or {@code null} for none */ public Operation setStatus(java.lang.String status) { this.status = status; return this; } /** * [Output Only] An optional textual description of the current status of the operation. * @return value or {@code null} for none */ public java.lang.String getStatusMessage() { return statusMessage; } /** * [Output Only] An optional textual description of the current status of the operation. * @param statusMessage statusMessage or {@code null} for none */ public Operation setStatusMessage(java.lang.String statusMessage) { this.statusMessage = statusMessage; return this; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @return value or {@code null} for none */ public java.math.BigInteger getTargetId() { return targetId; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @param targetId targetId or {@code null} for none */ public Operation setTargetId(java.math.BigInteger targetId) { this.targetId = targetId; return this; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @return value or {@code null} for none */ public java.lang.String getTargetLink() { return targetLink; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @param targetLink targetLink or {@code null} for none */ public Operation setTargetLink(java.lang.String targetLink) { this.targetLink = targetLink; return this; } /** * [Output Only] User who requested the operation, for example: `user@example.com`. * @return value or {@code null} for none */ public java.lang.String getUser() { return user; } /** * [Output Only] User who requested the operation, for example: `user@example.com`. * @param user user or {@code null} for none */ public Operation setUser(java.lang.String user) { this.user = user; return this; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @return value or {@code null} for none */ public java.util.List<Warnings> getWarnings() { return warnings; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @param warnings warnings or {@code null} for none */ public Operation setWarnings(java.util.List<Warnings> warnings) { this.warnings = warnings; return this; } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * @return value or {@code null} for none */ public java.lang.String getZone() { return zone; } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * @param zone zone or {@code null} for none */ public Operation setZone(java.lang.String zone) { this.zone = zone; return this; } @Override public Operation set(String fieldName, Object value) { return (Operation) super.set(fieldName, value); } @Override public Operation clone() { return (Operation) super.clone(); } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. */ public static final class Error extends com.google.api.client.json.GenericJson { /** * [Output Only] The array of errors encountered while processing this operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Errors> errors; static { // hack to force ProGuard to consider Errors 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(Errors.class); } /** * [Output Only] The array of errors encountered while processing this operation. * @return value or {@code null} for none */ public java.util.List<Errors> getErrors() { return errors; } /** * [Output Only] The array of errors encountered while processing this operation. * @param errors errors or {@code null} for none */ public Error setErrors(java.util.List<Errors> errors) { this.errors = errors; return this; } @Override public Error set(String fieldName, Object value) { return (Error) super.set(fieldName, value); } @Override public Error clone() { return (Error) super.clone(); } /** * Model definition for OperationErrorErrors. */ public static final class Errors extends com.google.api.client.json.GenericJson { /** * [Output Only] The error type identifier for this error. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ErrorDetails> errorDetails; static { // hack to force ProGuard to consider ErrorDetails 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(ErrorDetails.class); } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String location; /** * [Output Only] An optional, human-readable error message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] The error type identifier for this error. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] The error type identifier for this error. * @param code code or {@code null} for none */ public Errors setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * @return value or {@code null} for none */ public java.util.List<ErrorDetails> getErrorDetails() { return errorDetails; } /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * @param errorDetails errorDetails or {@code null} for none */ public Errors setErrorDetails(java.util.List<ErrorDetails> errorDetails) { this.errorDetails = errorDetails; return this; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @return value or {@code null} for none */ public java.lang.String getLocation() { return location; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @param location location or {@code null} for none */ public Errors setLocation(java.lang.String location) { this.location = location; return this; } /** * [Output Only] An optional, human-readable error message. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] An optional, human-readable error message. * @param message message or {@code null} for none */ public Errors setMessage(java.lang.String message) { this.message = message; return this; } @Override public Errors set(String fieldName, Object value) { return (Errors) super.set(fieldName, value); } @Override public Errors clone() { return (Errors) super.clone(); } /** * Model definition for OperationErrorErrorsErrorDetails. */ public static final class ErrorDetails extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private ErrorInfo errorInfo; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private Help help; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private LocalizedMessage localizedMessage; /** * @return value or {@code null} for none */ public ErrorInfo getErrorInfo() { return errorInfo; } /** * @param errorInfo errorInfo or {@code null} for none */ public ErrorDetails setErrorInfo(ErrorInfo errorInfo) { this.errorInfo = errorInfo; return this; } /** * @return value or {@code null} for none */ public Help getHelp() { return help; } /** * @param help help or {@code null} for none */ public ErrorDetails setHelp(Help help) { this.help = help; return this; } /** * @return value or {@code null} for none */ public LocalizedMessage getLocalizedMessage() { return localizedMessage; } /** * @param localizedMessage localizedMessage or {@code null} for none */ public ErrorDetails setLocalizedMessage(LocalizedMessage localizedMessage) { this.localizedMessage = localizedMessage; return this; } @Override public ErrorDetails set(String fieldName, Object value) { return (ErrorDetails) super.set(fieldName, value); } @Override public ErrorDetails clone() { return (ErrorDetails) super.clone(); } } } } /** * Model definition for OperationWarnings. */ public static final class Warnings extends com.google.api.client.json.GenericJson { /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Data> data; static { // hack to force ProGuard to consider Data 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(Data.class); } /** * [Output Only] A human-readable description of the warning code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @param code code or {@code null} for none */ public Warnings setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @return value or {@code null} for none */ public java.util.List<Data> getData() { return data; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @param data data or {@code null} for none */ public Warnings setData(java.util.List<Data> data) { this.data = data; return this; } /** * [Output Only] A human-readable description of the warning code. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] A human-readable description of the warning code. * @param message message or {@code null} for none */ public Warnings setMessage(java.lang.String message) { this.message = message; return this; } @Override public Warnings set(String fieldName, Object value) { return (Warnings) super.set(fieldName, value); } @Override public Warnings clone() { return (Warnings) super.clone(); } /** * Model definition for OperationWarningsData. */ public static final class Data extends com.google.api.client.json.GenericJson { /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String key; /** * [Output Only] A warning data value corresponding to the key. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String value; /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @return value or {@code null} for none */ public java.lang.String getKey() { return key; } /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @param key key or {@code null} for none */ public Data setKey(java.lang.String key) { this.key = key; return this; } /** * [Output Only] A warning data value corresponding to the key. * @return value or {@code null} for none */ public java.lang.String getValue() { return value; } /** * [Output Only] A warning data value corresponding to the key. * @param value value or {@code null} for none */ public Data setValue(java.lang.String value) { this.value = value; return this; } @Override public Data set(String fieldName, Object value) { return (Data) super.set(fieldName, value); } @Override public Data clone() { return (Data) super.clone(); } } } }
googleapis/google-cloud-java
35,346
java-meet/proto-google-cloud-meet-v2/src/main/java/com/google/apps/meet/v2/SpaceConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/meet/v2/resource.proto // Protobuf Java Version: 3.25.8 package com.google.apps.meet.v2; /** * * * <pre> * The configuration pertaining to a meeting space. * </pre> * * Protobuf type {@code google.apps.meet.v2.SpaceConfig} */ public final class SpaceConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.meet.v2.SpaceConfig) SpaceConfigOrBuilder { private static final long serialVersionUID = 0L; // Use SpaceConfig.newBuilder() to construct. private SpaceConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SpaceConfig() { accessType_ = 0; entryPointAccess_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SpaceConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_SpaceConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_SpaceConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.SpaceConfig.class, com.google.apps.meet.v2.SpaceConfig.Builder.class); } /** * * * <pre> * Possible access types for a meeting space. * </pre> * * Protobuf enum {@code google.apps.meet.v2.SpaceConfig.AccessType} */ public enum AccessType implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value specified by the user's organization. * Note: This is never returned, as the configured access type is * returned instead. * </pre> * * <code>ACCESS_TYPE_UNSPECIFIED = 0;</code> */ ACCESS_TYPE_UNSPECIFIED(0), /** * * * <pre> * Anyone with the join information (for example, the URL or phone access * information) can join without knocking. * </pre> * * <code>OPEN = 1;</code> */ OPEN(1), /** * * * <pre> * Members of the host's organization, invited external users, and dial-in * users can join without knocking. Everyone else must knock. * </pre> * * <code>TRUSTED = 2;</code> */ TRUSTED(2), /** * * * <pre> * Only invitees can join without knocking. Everyone else must knock. * </pre> * * <code>RESTRICTED = 3;</code> */ RESTRICTED(3), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value specified by the user's organization. * Note: This is never returned, as the configured access type is * returned instead. * </pre> * * <code>ACCESS_TYPE_UNSPECIFIED = 0;</code> */ public static final int ACCESS_TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Anyone with the join information (for example, the URL or phone access * information) can join without knocking. * </pre> * * <code>OPEN = 1;</code> */ public static final int OPEN_VALUE = 1; /** * * * <pre> * Members of the host's organization, invited external users, and dial-in * users can join without knocking. Everyone else must knock. * </pre> * * <code>TRUSTED = 2;</code> */ public static final int TRUSTED_VALUE = 2; /** * * * <pre> * Only invitees can join without knocking. Everyone else must knock. * </pre> * * <code>RESTRICTED = 3;</code> */ public static final int RESTRICTED_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 AccessType 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 AccessType forNumber(int value) { switch (value) { case 0: return ACCESS_TYPE_UNSPECIFIED; case 1: return OPEN; case 2: return TRUSTED; case 3: return RESTRICTED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<AccessType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<AccessType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<AccessType>() { public AccessType findValueByNumber(int number) { return AccessType.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.apps.meet.v2.SpaceConfig.getDescriptor().getEnumTypes().get(0); } private static final AccessType[] VALUES = values(); public static AccessType 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 AccessType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.apps.meet.v2.SpaceConfig.AccessType) } /** * * * <pre> * Entry points that can be used to join a meeting. Example: * `meet.google.com`, the Meet Embed SDK Web, or a mobile application. * </pre> * * Protobuf enum {@code google.apps.meet.v2.SpaceConfig.EntryPointAccess} */ public enum EntryPointAccess implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unused. * </pre> * * <code>ENTRY_POINT_ACCESS_UNSPECIFIED = 0;</code> */ ENTRY_POINT_ACCESS_UNSPECIFIED(0), /** * * * <pre> * All entry points are allowed. * </pre> * * <code>ALL = 1;</code> */ ALL(1), /** * * * <pre> * Only entry points owned by the Google Cloud project that created the * space can be used to join meetings in this space. Apps can use the Meet * Embed SDK Web or mobile Meet SDKs to create owned entry points. * </pre> * * <code>CREATOR_APP_ONLY = 2;</code> */ CREATOR_APP_ONLY(2), UNRECOGNIZED(-1), ; /** * * * <pre> * Unused. * </pre> * * <code>ENTRY_POINT_ACCESS_UNSPECIFIED = 0;</code> */ public static final int ENTRY_POINT_ACCESS_UNSPECIFIED_VALUE = 0; /** * * * <pre> * All entry points are allowed. * </pre> * * <code>ALL = 1;</code> */ public static final int ALL_VALUE = 1; /** * * * <pre> * Only entry points owned by the Google Cloud project that created the * space can be used to join meetings in this space. Apps can use the Meet * Embed SDK Web or mobile Meet SDKs to create owned entry points. * </pre> * * <code>CREATOR_APP_ONLY = 2;</code> */ public static final int CREATOR_APP_ONLY_VALUE = 2; 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 EntryPointAccess 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 EntryPointAccess forNumber(int value) { switch (value) { case 0: return ENTRY_POINT_ACCESS_UNSPECIFIED; case 1: return ALL; case 2: return CREATOR_APP_ONLY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<EntryPointAccess> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<EntryPointAccess> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<EntryPointAccess>() { public EntryPointAccess findValueByNumber(int number) { return EntryPointAccess.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.apps.meet.v2.SpaceConfig.getDescriptor().getEnumTypes().get(1); } private static final EntryPointAccess[] VALUES = values(); public static EntryPointAccess 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 EntryPointAccess(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.apps.meet.v2.SpaceConfig.EntryPointAccess) } public static final int ACCESS_TYPE_FIELD_NUMBER = 1; private int accessType_ = 0; /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @return The enum numeric value on the wire for accessType. */ @java.lang.Override public int getAccessTypeValue() { return accessType_; } /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @return The accessType. */ @java.lang.Override public com.google.apps.meet.v2.SpaceConfig.AccessType getAccessType() { com.google.apps.meet.v2.SpaceConfig.AccessType result = com.google.apps.meet.v2.SpaceConfig.AccessType.forNumber(accessType_); return result == null ? com.google.apps.meet.v2.SpaceConfig.AccessType.UNRECOGNIZED : result; } public static final int ENTRY_POINT_ACCESS_FIELD_NUMBER = 2; private int entryPointAccess_ = 0; /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @return The enum numeric value on the wire for entryPointAccess. */ @java.lang.Override public int getEntryPointAccessValue() { return entryPointAccess_; } /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @return The entryPointAccess. */ @java.lang.Override public com.google.apps.meet.v2.SpaceConfig.EntryPointAccess getEntryPointAccess() { com.google.apps.meet.v2.SpaceConfig.EntryPointAccess result = com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.forNumber(entryPointAccess_); return result == null ? com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.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 (accessType_ != com.google.apps.meet.v2.SpaceConfig.AccessType.ACCESS_TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, accessType_); } if (entryPointAccess_ != com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.ENTRY_POINT_ACCESS_UNSPECIFIED .getNumber()) { output.writeEnum(2, entryPointAccess_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (accessType_ != com.google.apps.meet.v2.SpaceConfig.AccessType.ACCESS_TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, accessType_); } if (entryPointAccess_ != com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.ENTRY_POINT_ACCESS_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, entryPointAccess_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.meet.v2.SpaceConfig)) { return super.equals(obj); } com.google.apps.meet.v2.SpaceConfig other = (com.google.apps.meet.v2.SpaceConfig) obj; if (accessType_ != other.accessType_) return false; if (entryPointAccess_ != other.entryPointAccess_) 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) + ACCESS_TYPE_FIELD_NUMBER; hash = (53 * hash) + accessType_; hash = (37 * hash) + ENTRY_POINT_ACCESS_FIELD_NUMBER; hash = (53 * hash) + entryPointAccess_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.meet.v2.SpaceConfig parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.SpaceConfig parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.SpaceConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.SpaceConfig parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.SpaceConfig parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.meet.v2.SpaceConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.SpaceConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.apps.meet.v2.SpaceConfig 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 configuration pertaining to a meeting space. * </pre> * * Protobuf type {@code google.apps.meet.v2.SpaceConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.meet.v2.SpaceConfig) com.google.apps.meet.v2.SpaceConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_SpaceConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_SpaceConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.SpaceConfig.class, com.google.apps.meet.v2.SpaceConfig.Builder.class); } // Construct using com.google.apps.meet.v2.SpaceConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; accessType_ = 0; entryPointAccess_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_SpaceConfig_descriptor; } @java.lang.Override public com.google.apps.meet.v2.SpaceConfig getDefaultInstanceForType() { return com.google.apps.meet.v2.SpaceConfig.getDefaultInstance(); } @java.lang.Override public com.google.apps.meet.v2.SpaceConfig build() { com.google.apps.meet.v2.SpaceConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.meet.v2.SpaceConfig buildPartial() { com.google.apps.meet.v2.SpaceConfig result = new com.google.apps.meet.v2.SpaceConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.apps.meet.v2.SpaceConfig result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.accessType_ = accessType_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.entryPointAccess_ = entryPointAccess_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.meet.v2.SpaceConfig) { return mergeFrom((com.google.apps.meet.v2.SpaceConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.meet.v2.SpaceConfig other) { if (other == com.google.apps.meet.v2.SpaceConfig.getDefaultInstance()) return this; if (other.accessType_ != 0) { setAccessTypeValue(other.getAccessTypeValue()); } if (other.entryPointAccess_ != 0) { setEntryPointAccessValue(other.getEntryPointAccessValue()); } 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: { accessType_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { entryPointAccess_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int accessType_ = 0; /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @return The enum numeric value on the wire for accessType. */ @java.lang.Override public int getAccessTypeValue() { return accessType_; } /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @param value The enum numeric value on the wire for accessType to set. * @return This builder for chaining. */ public Builder setAccessTypeValue(int value) { accessType_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @return The accessType. */ @java.lang.Override public com.google.apps.meet.v2.SpaceConfig.AccessType getAccessType() { com.google.apps.meet.v2.SpaceConfig.AccessType result = com.google.apps.meet.v2.SpaceConfig.AccessType.forNumber(accessType_); return result == null ? com.google.apps.meet.v2.SpaceConfig.AccessType.UNRECOGNIZED : result; } /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @param value The accessType to set. * @return This builder for chaining. */ public Builder setAccessType(com.google.apps.meet.v2.SpaceConfig.AccessType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; accessType_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Access type of the meeting space that determines who can join without * knocking. Default: The user's default access settings. Controlled by the * user's admin for enterprise users or RESTRICTED. * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.AccessType access_type = 1;</code> * * @return This builder for chaining. */ public Builder clearAccessType() { bitField0_ = (bitField0_ & ~0x00000001); accessType_ = 0; onChanged(); return this; } private int entryPointAccess_ = 0; /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @return The enum numeric value on the wire for entryPointAccess. */ @java.lang.Override public int getEntryPointAccessValue() { return entryPointAccess_; } /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @param value The enum numeric value on the wire for entryPointAccess to set. * @return This builder for chaining. */ public Builder setEntryPointAccessValue(int value) { entryPointAccess_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @return The entryPointAccess. */ @java.lang.Override public com.google.apps.meet.v2.SpaceConfig.EntryPointAccess getEntryPointAccess() { com.google.apps.meet.v2.SpaceConfig.EntryPointAccess result = com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.forNumber(entryPointAccess_); return result == null ? com.google.apps.meet.v2.SpaceConfig.EntryPointAccess.UNRECOGNIZED : result; } /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @param value The entryPointAccess to set. * @return This builder for chaining. */ public Builder setEntryPointAccess(com.google.apps.meet.v2.SpaceConfig.EntryPointAccess value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; entryPointAccess_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Defines the entry points that can be used to join meetings hosted in this * meeting space. * Default: EntryPointAccess.ALL * </pre> * * <code>.google.apps.meet.v2.SpaceConfig.EntryPointAccess entry_point_access = 2;</code> * * @return This builder for chaining. */ public Builder clearEntryPointAccess() { bitField0_ = (bitField0_ & ~0x00000002); entryPointAccess_ = 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.apps.meet.v2.SpaceConfig) } // @@protoc_insertion_point(class_scope:google.apps.meet.v2.SpaceConfig) private static final com.google.apps.meet.v2.SpaceConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.meet.v2.SpaceConfig(); } public static com.google.apps.meet.v2.SpaceConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SpaceConfig> PARSER = new com.google.protobuf.AbstractParser<SpaceConfig>() { @java.lang.Override public SpaceConfig 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<SpaceConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SpaceConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.meet.v2.SpaceConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/fluss
35,752
fluss-server/src/main/java/org/apache/fluss/server/coordinator/CoordinatorService.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.fluss.server.coordinator; import org.apache.fluss.annotation.VisibleForTesting; import org.apache.fluss.cluster.ServerType; import org.apache.fluss.cluster.TabletServerInfo; import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.config.cluster.AlterConfig; import org.apache.fluss.config.cluster.AlterConfigOpType; import org.apache.fluss.exception.InvalidAlterTableException; import org.apache.fluss.exception.InvalidCoordinatorException; import org.apache.fluss.exception.InvalidDatabaseException; import org.apache.fluss.exception.InvalidTableException; import org.apache.fluss.exception.LakeTableAlreadyExistException; import org.apache.fluss.exception.SecurityDisabledException; import org.apache.fluss.exception.TableAlreadyExistException; import org.apache.fluss.exception.TableNotPartitionedException; import org.apache.fluss.fs.FileSystem; import org.apache.fluss.metadata.DataLakeFormat; import org.apache.fluss.metadata.DatabaseDescriptor; import org.apache.fluss.metadata.PartitionSpec; import org.apache.fluss.metadata.ResolvedPartitionSpec; import org.apache.fluss.metadata.TableChange; import org.apache.fluss.metadata.TableDescriptor; import org.apache.fluss.metadata.TablePath; import org.apache.fluss.rpc.gateway.CoordinatorGateway; import org.apache.fluss.rpc.messages.AdjustIsrRequest; import org.apache.fluss.rpc.messages.AdjustIsrResponse; import org.apache.fluss.rpc.messages.AlterClusterConfigsRequest; import org.apache.fluss.rpc.messages.AlterClusterConfigsResponse; import org.apache.fluss.rpc.messages.AlterTableRequest; import org.apache.fluss.rpc.messages.AlterTableResponse; import org.apache.fluss.rpc.messages.CommitKvSnapshotRequest; import org.apache.fluss.rpc.messages.CommitKvSnapshotResponse; import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotRequest; import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotResponse; import org.apache.fluss.rpc.messages.CommitRemoteLogManifestRequest; import org.apache.fluss.rpc.messages.CommitRemoteLogManifestResponse; import org.apache.fluss.rpc.messages.ControlledShutdownRequest; import org.apache.fluss.rpc.messages.ControlledShutdownResponse; import org.apache.fluss.rpc.messages.CreateAclsRequest; import org.apache.fluss.rpc.messages.CreateAclsResponse; import org.apache.fluss.rpc.messages.CreateDatabaseRequest; import org.apache.fluss.rpc.messages.CreateDatabaseResponse; import org.apache.fluss.rpc.messages.CreatePartitionRequest; import org.apache.fluss.rpc.messages.CreatePartitionResponse; import org.apache.fluss.rpc.messages.CreateTableRequest; import org.apache.fluss.rpc.messages.CreateTableResponse; import org.apache.fluss.rpc.messages.DropAclsRequest; import org.apache.fluss.rpc.messages.DropAclsResponse; import org.apache.fluss.rpc.messages.DropDatabaseRequest; import org.apache.fluss.rpc.messages.DropDatabaseResponse; import org.apache.fluss.rpc.messages.DropPartitionRequest; import org.apache.fluss.rpc.messages.DropPartitionResponse; import org.apache.fluss.rpc.messages.DropTableRequest; import org.apache.fluss.rpc.messages.DropTableResponse; import org.apache.fluss.rpc.messages.LakeTieringHeartbeatRequest; import org.apache.fluss.rpc.messages.LakeTieringHeartbeatResponse; import org.apache.fluss.rpc.messages.MetadataRequest; import org.apache.fluss.rpc.messages.MetadataResponse; import org.apache.fluss.rpc.messages.PbAlterConfig; import org.apache.fluss.rpc.messages.PbHeartbeatReqForTable; import org.apache.fluss.rpc.messages.PbHeartbeatRespForTable; import org.apache.fluss.rpc.netty.server.Session; import org.apache.fluss.rpc.protocol.ApiError; import org.apache.fluss.security.acl.AclBinding; import org.apache.fluss.security.acl.AclBindingFilter; import org.apache.fluss.security.acl.OperationType; import org.apache.fluss.security.acl.Resource; import org.apache.fluss.server.DynamicConfigManager; import org.apache.fluss.server.RpcServiceBase; import org.apache.fluss.server.authorizer.AclCreateResult; import org.apache.fluss.server.authorizer.AclDeleteResult; import org.apache.fluss.server.authorizer.Authorizer; import org.apache.fluss.server.coordinator.event.AccessContextEvent; import org.apache.fluss.server.coordinator.event.AdjustIsrReceivedEvent; import org.apache.fluss.server.coordinator.event.CommitKvSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitLakeTableSnapshotEvent; import org.apache.fluss.server.coordinator.event.CommitRemoteLogManifestEvent; import org.apache.fluss.server.coordinator.event.ControlledShutdownEvent; import org.apache.fluss.server.coordinator.event.EventManager; import org.apache.fluss.server.entity.CommitKvSnapshotData; import org.apache.fluss.server.entity.LakeTieringTableInfo; import org.apache.fluss.server.entity.TablePropertyChanges; import org.apache.fluss.server.kv.snapshot.CompletedSnapshot; import org.apache.fluss.server.kv.snapshot.CompletedSnapshotJsonSerde; import org.apache.fluss.server.metadata.CoordinatorMetadataCache; import org.apache.fluss.server.metadata.CoordinatorMetadataProvider; import org.apache.fluss.server.zk.ZooKeeperClient; import org.apache.fluss.server.zk.data.BucketAssignment; import org.apache.fluss.server.zk.data.PartitionAssignment; import org.apache.fluss.server.zk.data.TableAssignment; import org.apache.fluss.server.zk.data.TableRegistration; import org.apache.fluss.utils.IOUtils; import org.apache.fluss.utils.concurrent.FutureUtils; import javax.annotation.Nullable; import java.io.UncheckedIOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; import static org.apache.fluss.config.FlussConfigUtils.isTableStorageConfig; import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.toAclBindingFilters; import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.toAclBindings; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.fromTablePath; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getAdjustIsrData; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getCommitLakeTableSnapshotData; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getCommitRemoteLogManifestData; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getPartitionSpec; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.makeCreateAclsResponse; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.makeDropAclsResponse; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.toTableChanges; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.toTablePath; import static org.apache.fluss.server.utils.TableAssignmentUtils.generateAssignment; import static org.apache.fluss.utils.PartitionUtils.validatePartitionSpec; import static org.apache.fluss.utils.Preconditions.checkNotNull; /** An RPC Gateway service for coordinator server. */ public final class CoordinatorService extends RpcServiceBase implements CoordinatorGateway { private final int defaultBucketNumber; private final int defaultReplicationFactor; private final boolean logTableAllowCreation; private final boolean kvTableAllowCreation; private final Supplier<EventManager> eventManagerSupplier; private final Supplier<Integer> coordinatorEpochSupplier; private final CoordinatorMetadataCache metadataCache; private final LakeTableTieringManager lakeTableTieringManager; private final LakeCatalogDynamicLoader lakeCatalogDynamicLoader; public CoordinatorService( Configuration conf, FileSystem remoteFileSystem, ZooKeeperClient zkClient, Supplier<CoordinatorEventProcessor> coordinatorEventProcessorSupplier, CoordinatorMetadataCache metadataCache, MetadataManager metadataManager, @Nullable Authorizer authorizer, LakeCatalogDynamicLoader lakeCatalogDynamicLoader, LakeTableTieringManager lakeTableTieringManager, DynamicConfigManager dynamicConfigManager) { super( remoteFileSystem, ServerType.COORDINATOR, zkClient, metadataManager, authorizer, dynamicConfigManager); this.defaultBucketNumber = conf.getInt(ConfigOptions.DEFAULT_BUCKET_NUMBER); this.defaultReplicationFactor = conf.getInt(ConfigOptions.DEFAULT_REPLICATION_FACTOR); this.logTableAllowCreation = conf.getBoolean(ConfigOptions.LOG_TABLE_ALLOW_CREATION); this.kvTableAllowCreation = conf.getBoolean(ConfigOptions.KV_TABLE_ALLOW_CREATION); this.eventManagerSupplier = () -> coordinatorEventProcessorSupplier.get().getCoordinatorEventManager(); this.coordinatorEpochSupplier = () -> coordinatorEventProcessorSupplier.get().getCoordinatorEpoch(); this.lakeTableTieringManager = lakeTableTieringManager; this.metadataCache = metadataCache; this.lakeCatalogDynamicLoader = lakeCatalogDynamicLoader; } @Override public String name() { return "coordinator"; } @Override public void shutdown() { IOUtils.closeQuietly(lakeCatalogDynamicLoader, "lake catalog"); } @Override public CompletableFuture<CreateDatabaseResponse> createDatabase(CreateDatabaseRequest request) { if (authorizer != null) { authorizer.authorize(currentSession(), OperationType.CREATE, Resource.cluster()); } CreateDatabaseResponse response = new CreateDatabaseResponse(); try { TablePath.validateDatabaseName(request.getDatabaseName()); } catch (InvalidDatabaseException e) { return FutureUtils.completedExceptionally(e); } DatabaseDescriptor databaseDescriptor; if (request.getDatabaseJson() != null) { databaseDescriptor = DatabaseDescriptor.fromJsonBytes(request.getDatabaseJson()); } else { databaseDescriptor = DatabaseDescriptor.builder().build(); } metadataManager.createDatabase( request.getDatabaseName(), databaseDescriptor, request.isIgnoreIfExists()); return CompletableFuture.completedFuture(response); } @Override public CompletableFuture<DropDatabaseResponse> dropDatabase(DropDatabaseRequest request) { if (authorizer != null) { authorizer.authorize( currentSession(), OperationType.DROP, Resource.database(request.getDatabaseName())); } DropDatabaseResponse response = new DropDatabaseResponse(); metadataManager.dropDatabase( request.getDatabaseName(), request.isIgnoreIfNotExists(), request.isCascade()); return CompletableFuture.completedFuture(response); } @Override public CompletableFuture<CreateTableResponse> createTable(CreateTableRequest request) { TablePath tablePath = toTablePath(request.getTablePath()); tablePath.validate(); if (authorizer != null) { authorizer.authorize( currentSession(), OperationType.CREATE, Resource.database(tablePath.getDatabaseName())); } TableDescriptor tableDescriptor; try { tableDescriptor = TableDescriptor.fromJsonBytes(request.getTableJson()); } catch (Exception e) { if (e instanceof UncheckedIOException) { throw new InvalidTableException( "Failed to parse table descriptor: " + e.getMessage()); } else { // wrap the validate message to InvalidTableException throw new InvalidTableException(e.getMessage()); } } LakeCatalogDynamicLoader.LakeCatalogContainer lakeCatalogContainer = lakeCatalogDynamicLoader.getLakeCatalogContainer(); // Check table creation permissions based on table type validateTableCreationPermission(tableDescriptor, tablePath); // apply system defaults if the config is not set tableDescriptor = applySystemDefaults(tableDescriptor, lakeCatalogContainer.getDataLakeFormat()); // the distribution and bucket count must be set now //noinspection OptionalGetWithoutIsPresent int bucketCount = tableDescriptor.getTableDistribution().get().getBucketCount().get(); // first, generate the assignment TableAssignment tableAssignment = null; // only when it's no partitioned table do we generate the assignment for it if (!tableDescriptor.isPartitioned()) { // the replication factor must be set now int replicaFactor = tableDescriptor.getReplicationFactor(); TabletServerInfo[] servers = metadataCache.getLiveServers(); tableAssignment = generateAssignment(bucketCount, replicaFactor, servers); } // TODO: should tolerate if the lake exist but matches our schema. This ensures eventually // consistent by idempotently creating the table multiple times. See #846 // before create table in fluss, we may create in lake if (isDataLakeEnabled(tableDescriptor)) { try { checkNotNull(lakeCatalogContainer.getLakeCatalog()) .createTable(tablePath, tableDescriptor); } catch (TableAlreadyExistException e) { throw new LakeTableAlreadyExistException( String.format( "The table %s already exists in %s catalog, please " + "first drop the table in %s catalog or use a new table name.", tablePath, lakeCatalogContainer.getDataLakeFormat(), lakeCatalogContainer.getDataLakeFormat())); } } // then create table; metadataManager.createTable( tablePath, tableDescriptor, tableAssignment, request.isIgnoreIfExists()); return CompletableFuture.completedFuture(new CreateTableResponse()); } @Override public CompletableFuture<AlterTableResponse> alterTable(AlterTableRequest request) { TablePath tablePath = toTablePath(request.getTablePath()); tablePath.validate(); if (authorizer != null) { authorizer.authorize(currentSession(), OperationType.ALTER, Resource.table(tablePath)); } List<TableChange> tableChanges = toTableChanges(request.getConfigChangesList()); TablePropertyChanges tablePropertyChanges = toTablePropertyChanges(tableChanges); LakeCatalogDynamicLoader.LakeCatalogContainer lakeCatalogContainer = lakeCatalogDynamicLoader.getLakeCatalogContainer(); metadataManager.alterTableProperties( tablePath, tableChanges, tablePropertyChanges, request.isIgnoreIfNotExists(), lakeCatalogContainer.getLakeCatalog(), lakeCatalogContainer.getDataLakeFormat(), lakeTableTieringManager); return CompletableFuture.completedFuture(new AlterTableResponse()); } public static TablePropertyChanges toTablePropertyChanges(List<TableChange> tableChanges) { TablePropertyChanges.Builder builder = TablePropertyChanges.builder(); if (tableChanges.isEmpty()) { return builder.build(); } for (TableChange tableChange : tableChanges) { if (tableChange instanceof TableChange.SetOption) { TableChange.SetOption setOption = (TableChange.SetOption) tableChange; String optionKey = setOption.getKey(); if (isTableStorageConfig(optionKey)) { builder.setTableProperty(optionKey, setOption.getValue()); } else { // otherwise, it's considered as custom property builder.setCustomProperty(optionKey, setOption.getValue()); } } else if (tableChange instanceof TableChange.ResetOption) { TableChange.ResetOption resetOption = (TableChange.ResetOption) tableChange; String optionKey = resetOption.getKey(); if (isTableStorageConfig(optionKey)) { builder.resetTableProperty(optionKey); } else { // otherwise, it's considered as custom property builder.resetCustomProperty(optionKey); } } else { throw new InvalidAlterTableException( "Unsupported alter table change: " + tableChange); } } return builder.build(); } private TableDescriptor applySystemDefaults( TableDescriptor tableDescriptor, DataLakeFormat dataLakeFormat) { TableDescriptor newDescriptor = tableDescriptor; // not set bucket num if (!newDescriptor.getTableDistribution().isPresent() || !newDescriptor.getTableDistribution().get().getBucketCount().isPresent()) { newDescriptor = newDescriptor.withBucketCount(defaultBucketNumber); } // not set replication factor Map<String, String> properties = newDescriptor.getProperties(); if (!properties.containsKey(ConfigOptions.TABLE_REPLICATION_FACTOR.key())) { newDescriptor = newDescriptor.withReplicationFactor(defaultReplicationFactor); } // override set num-precreate for auto-partition table with multi-level partition keys if (newDescriptor.getPartitionKeys().size() > 1 && "true".equals(properties.get(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED.key())) && !properties.containsKey( ConfigOptions.TABLE_AUTO_PARTITION_NUM_PRECREATE.key())) { Map<String, String> newProperties = new HashMap<>(newDescriptor.getProperties()); // disable precreate partitions for multi-level partitions. newProperties.put(ConfigOptions.TABLE_AUTO_PARTITION_NUM_PRECREATE.key(), "0"); newDescriptor = newDescriptor.withProperties(newProperties); } // override the datalake format if the table hasn't set it and the cluster configured if (dataLakeFormat != null && !properties.containsKey(ConfigOptions.TABLE_DATALAKE_FORMAT.key())) { newDescriptor = newDescriptor.withDataLakeFormat(dataLakeFormat); } // lake table can only be enabled when the cluster configures datalake format boolean dataLakeEnabled = isDataLakeEnabled(tableDescriptor); if (dataLakeEnabled && dataLakeFormat == null) { throw new InvalidTableException( String.format( "'%s' is enabled for the table, but the Fluss cluster doesn't enable datalake tables.", ConfigOptions.TABLE_DATALAKE_ENABLED.key())); } return newDescriptor; } private boolean isDataLakeEnabled(TableDescriptor tableDescriptor) { String dataLakeEnabledValue = tableDescriptor.getProperties().get(ConfigOptions.TABLE_DATALAKE_ENABLED.key()); return Boolean.parseBoolean(dataLakeEnabledValue); } @Override public CompletableFuture<DropTableResponse> dropTable(DropTableRequest request) { TablePath tablePath = toTablePath(request.getTablePath()); if (authorizer != null) { authorizer.authorize( currentSession(), OperationType.DROP, Resource.table(tablePath.getDatabaseName(), tablePath.getTableName())); } DropTableResponse response = new DropTableResponse(); metadataManager.dropTable(tablePath, request.isIgnoreIfNotExists()); return CompletableFuture.completedFuture(response); } @Override public CompletableFuture<CreatePartitionResponse> createPartition( CreatePartitionRequest request) { TablePath tablePath = toTablePath(request.getTablePath()); if (authorizer != null) { authorizer.authorize( currentSession(), OperationType.WRITE, Resource.table(tablePath.getDatabaseName(), tablePath.getTableName())); } CreatePartitionResponse response = new CreatePartitionResponse(); TableRegistration table = metadataManager.getTableRegistration(tablePath); if (!table.isPartitioned()) { throw new TableNotPartitionedException( "Only partitioned table support create partition."); } // first, validate the partition spec, and get resolved partition spec. PartitionSpec partitionSpec = getPartitionSpec(request.getPartitionSpec()); validatePartitionSpec(tablePath, table.partitionKeys, partitionSpec); ResolvedPartitionSpec partitionToCreate = ResolvedPartitionSpec.fromPartitionSpec(table.partitionKeys, partitionSpec); // second, generate the PartitionAssignment. int replicaFactor = table.getTableConfig().getReplicationFactor(); TabletServerInfo[] servers = metadataCache.getLiveServers(); Map<Integer, BucketAssignment> bucketAssignments = generateAssignment(table.bucketCount, replicaFactor, servers) .getBucketAssignments(); PartitionAssignment partitionAssignment = new PartitionAssignment(table.tableId, bucketAssignments); metadataManager.createPartition( tablePath, table.tableId, partitionAssignment, partitionToCreate, request.isIgnoreIfNotExists()); return CompletableFuture.completedFuture(response); } @Override public CompletableFuture<DropPartitionResponse> dropPartition(DropPartitionRequest request) { TablePath tablePath = toTablePath(request.getTablePath()); if (authorizer != null) { authorizer.authorize( currentSession(), OperationType.WRITE, Resource.table(tablePath.getDatabaseName(), tablePath.getTableName())); } DropPartitionResponse response = new DropPartitionResponse(); TableRegistration table = metadataManager.getTableRegistration(tablePath); if (!table.isPartitioned()) { throw new TableNotPartitionedException( "Only partitioned table support drop partition."); } // first, validate the partition spec. PartitionSpec partitionSpec = getPartitionSpec(request.getPartitionSpec()); validatePartitionSpec(tablePath, table.partitionKeys, partitionSpec); ResolvedPartitionSpec partitionToDrop = ResolvedPartitionSpec.fromPartitionSpec(table.partitionKeys, partitionSpec); metadataManager.dropPartition(tablePath, partitionToDrop, request.isIgnoreIfNotExists()); return CompletableFuture.completedFuture(response); } @Override public CompletableFuture<MetadataResponse> metadata(MetadataRequest request) { String listenerName = currentListenerName(); Session session = currentSession(); AccessContextEvent<MetadataResponse> metadataResponseAccessContextEvent = new AccessContextEvent<>( ctx -> { return processMetadataRequest( request, listenerName, session, authorizer, metadataCache, new CoordinatorMetadataProvider( zkClient, metadataManager, ctx)); }); eventManagerSupplier.get().put(metadataResponseAccessContextEvent); return metadataResponseAccessContextEvent.getResultFuture(); } public CompletableFuture<AdjustIsrResponse> adjustIsr(AdjustIsrRequest request) { CompletableFuture<AdjustIsrResponse> response = new CompletableFuture<>(); eventManagerSupplier .get() .put(new AdjustIsrReceivedEvent(getAdjustIsrData(request), response)); return response; } @Override public CompletableFuture<CommitKvSnapshotResponse> commitKvSnapshot( CommitKvSnapshotRequest request) { CompletableFuture<CommitKvSnapshotResponse> response = new CompletableFuture<>(); // parse completed snapshot from request byte[] completedSnapshotBytes = request.getCompletedSnapshot(); CompletedSnapshot completedSnapshot = CompletedSnapshotJsonSerde.fromJson(completedSnapshotBytes); CommitKvSnapshotData commitKvSnapshotData = new CommitKvSnapshotData( completedSnapshot, request.getCoordinatorEpoch(), request.getBucketLeaderEpoch()); eventManagerSupplier.get().put(new CommitKvSnapshotEvent(commitKvSnapshotData, response)); return response; } @Override public CompletableFuture<CommitRemoteLogManifestResponse> commitRemoteLogManifest( CommitRemoteLogManifestRequest request) { CompletableFuture<CommitRemoteLogManifestResponse> response = new CompletableFuture<>(); eventManagerSupplier .get() .put( new CommitRemoteLogManifestEvent( getCommitRemoteLogManifestData(request), response)); return response; } @Override public CompletableFuture<CreateAclsResponse> createAcls(CreateAclsRequest request) { if (authorizer == null) { throw new SecurityDisabledException("No Authorizer is configured."); } List<AclBinding> aclBindings = toAclBindings(request.getAclsList()); List<AclCreateResult> aclCreateResults = authorizer.addAcls(currentSession(), aclBindings); return CompletableFuture.completedFuture(makeCreateAclsResponse(aclCreateResults)); } @Override public CompletableFuture<DropAclsResponse> dropAcls(DropAclsRequest request) { if (authorizer == null) { throw new SecurityDisabledException("No Authorizer is configured."); } List<AclBindingFilter> filters = toAclBindingFilters(request.getAclFiltersList()); List<AclDeleteResult> aclDeleteResults = authorizer.dropAcls(currentSession(), filters); return CompletableFuture.completedFuture(makeDropAclsResponse(aclDeleteResults)); } @Override public CompletableFuture<CommitLakeTableSnapshotResponse> commitLakeTableSnapshot( CommitLakeTableSnapshotRequest request) { CompletableFuture<CommitLakeTableSnapshotResponse> response = new CompletableFuture<>(); eventManagerSupplier .get() .put( new CommitLakeTableSnapshotEvent( getCommitLakeTableSnapshotData(request), response)); return response; } @Override public CompletableFuture<LakeTieringHeartbeatResponse> lakeTieringHeartbeat( LakeTieringHeartbeatRequest request) { LakeTieringHeartbeatResponse heartbeatResponse = new LakeTieringHeartbeatResponse(); int currentCoordinatorEpoch = coordinatorEpochSupplier.get(); heartbeatResponse.setCoordinatorEpoch(currentCoordinatorEpoch); // process failed tables for (PbHeartbeatReqForTable failedTable : request.getFailedTablesList()) { PbHeartbeatRespForTable pbHeartbeatRespForTable = heartbeatResponse.addFailedTableResp().setTableId(failedTable.getTableId()); try { validateHeartbeatRequest(failedTable, currentCoordinatorEpoch); lakeTableTieringManager.reportTieringFail( failedTable.getTableId(), failedTable.getTieringEpoch()); } catch (Throwable e) { pbHeartbeatRespForTable.setError(ApiError.fromThrowable(e).toErrorResponse()); } } // process tiering tables for (PbHeartbeatReqForTable tieringTable : request.getTieringTablesList()) { PbHeartbeatRespForTable pbHeartbeatRespForTable = heartbeatResponse.addTieringTableResp().setTableId(tieringTable.getTableId()); try { validateHeartbeatRequest(tieringTable, currentCoordinatorEpoch); lakeTableTieringManager.renewTieringHeartbeat( tieringTable.getTableId(), tieringTable.getTieringEpoch()); } catch (Throwable t) { pbHeartbeatRespForTable.setError(ApiError.fromThrowable(t).toErrorResponse()); } } // process finished tables for (PbHeartbeatReqForTable finishTable : request.getFinishedTablesList()) { PbHeartbeatRespForTable pbHeartbeatRespForTable = heartbeatResponse.addFinishedTableResp().setTableId(finishTable.getTableId()); try { validateHeartbeatRequest(finishTable, currentCoordinatorEpoch); lakeTableTieringManager.finishTableTiering( finishTable.getTableId(), finishTable.getTieringEpoch()); } catch (Throwable e) { pbHeartbeatRespForTable.setError(ApiError.fromThrowable(e).toErrorResponse()); } } if (request.hasRequestTable() && request.isRequestTable()) { LakeTieringTableInfo lakeTieringTableInfo = lakeTableTieringManager.requestTable(); if (lakeTieringTableInfo != null) { heartbeatResponse .setTieringTable() .setTableId(lakeTieringTableInfo.tableId()) .setTablePath(fromTablePath(lakeTieringTableInfo.tablePath())) .setTieringEpoch(lakeTieringTableInfo.tieringEpoch()); } } return CompletableFuture.completedFuture(heartbeatResponse); } @Override public CompletableFuture<ControlledShutdownResponse> controlledShutdown( ControlledShutdownRequest request) { CompletableFuture<ControlledShutdownResponse> response = new CompletableFuture<>(); eventManagerSupplier .get() .put( new ControlledShutdownEvent( request.getTabletServerId(), request.getTabletServerEpoch(), response)); return response; } @Override public CompletableFuture<AlterClusterConfigsResponse> alterClusterConfigs( AlterClusterConfigsRequest request) { CompletableFuture<AlterClusterConfigsResponse> future = new CompletableFuture<>(); List<PbAlterConfig> infos = request.getAlterConfigsList(); if (infos.isEmpty()) { return CompletableFuture.completedFuture(new AlterClusterConfigsResponse()); } if (authorizer != null) { authorizer.authorize(currentSession(), OperationType.ALTER, Resource.cluster()); } List<AlterConfig> serverConfigChanges = infos.stream() .map( info -> new AlterConfig( info.getConfigKey(), info.hasConfigValue() ? info.getConfigValue() : null, AlterConfigOpType.from((byte) info.getOpType()))) .collect(Collectors.toList()); AccessContextEvent<Void> accessContextEvent = new AccessContextEvent<>( (context) -> { try { dynamicConfigManager.alterConfigs(serverConfigChanges); future.complete(new AlterClusterConfigsResponse()); } catch (Exception e) { future.completeExceptionally(e); } return null; }); eventManagerSupplier.get().put(accessContextEvent); return future; } @VisibleForTesting public DataLakeFormat getDataLakeFormat() { return lakeCatalogDynamicLoader.getLakeCatalogContainer().getDataLakeFormat(); } private void validateHeartbeatRequest( PbHeartbeatReqForTable heartbeatReqForTable, int currentEpoch) { if (heartbeatReqForTable.getCoordinatorEpoch() != currentEpoch) { throw new InvalidCoordinatorException( String.format( "The coordinator epoch %s in request is not match current coordinator epoch %d for table %d.", heartbeatReqForTable.getCoordinatorEpoch(), currentEpoch, heartbeatReqForTable.getTableId())); } } /** * Validates whether the table creation is allowed based on the table type and configuration. * * @param tableDescriptor the table descriptor to validate * @param tablePath the table path for error reporting * @throws InvalidTableException if table creation is not allowed */ private void validateTableCreationPermission( TableDescriptor tableDescriptor, TablePath tablePath) { boolean hasPrimaryKey = tableDescriptor.hasPrimaryKey(); if (hasPrimaryKey) { // This is a KV table (Primary Key Table) if (!kvTableAllowCreation) { throw new InvalidTableException( "Creation of Primary Key Tables is disallowed in the cluster."); } } else { // This is a Log table if (!logTableAllowCreation) { throw new InvalidTableException( "Creation of Log Tables is disallowed in the cluster."); } } } }
apache/gobblin
35,727
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinHelixJobLauncher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.cluster; import com.google.common.eventbus.Subscribe; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import org.apache.gobblin.runtime.SourceDecorator; import org.apache.gobblin.source.extractor.extract.kafka.KafkaPartition; import org.apache.gobblin.source.extractor.extract.kafka.KafkaSource; import org.apache.gobblin.source.extractor.extract.kafka.KafkaUtils; import org.apache.gobblin.source.workunit.BasicWorkUnitStream; import org.apache.gobblin.source.workunit.WorkUnitStream; import org.apache.gobblin.stream.WorkUnitChangeEvent; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.helix.HelixManager; import org.apache.helix.task.JobConfig; import org.apache.helix.task.JobQueue; import org.apache.helix.task.TaskConfig; import org.apache.helix.task.TaskDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.rholder.retry.RetryException; import com.github.rholder.retry.Retryer; import com.github.rholder.retry.RetryerBuilder; import com.github.rholder.retry.StopStrategies; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.typesafe.config.Config; import com.typesafe.config.ConfigValueFactory; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.annotation.Alpha; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.metastore.StateStore; import org.apache.gobblin.metrics.Tag; import org.apache.gobblin.metrics.event.CountEventBuilder; import org.apache.gobblin.metrics.event.JobEvent; import org.apache.gobblin.metrics.event.TimingEvent; import org.apache.gobblin.rest.LauncherTypeEnum; import org.apache.gobblin.runtime.AbstractJobLauncher; import org.apache.gobblin.runtime.ExecutionModel; import org.apache.gobblin.runtime.JobException; import org.apache.gobblin.runtime.JobLauncher; import org.apache.gobblin.runtime.JobState; import org.apache.gobblin.runtime.Task; import org.apache.gobblin.runtime.TaskState; import org.apache.gobblin.runtime.TaskStateCollectorService; import org.apache.gobblin.runtime.listeners.JobListener; import org.apache.gobblin.runtime.util.StateStores; import org.apache.gobblin.source.workunit.WorkUnit; import org.apache.gobblin.util.ConfigUtils; import org.apache.gobblin.util.JobLauncherUtils; import org.apache.gobblin.util.ParallelRunner; import org.apache.gobblin.util.PropertiesUtils; import org.apache.gobblin.util.SerializationUtils; import static org.apache.gobblin.util.JobLauncherUtils.*; /** * An implementation of {@link JobLauncher} that launches a Gobblin job using the Helix task framework. * * <p> * This class uses the Helix task execution framework to run tasks of Gobblin jobs. It creates one Helix * {@link JobQueue} per job and submits every scheduled runs of a job to its {@link JobQueue}, where Helix * picks up them and submit them for execution. After submitting the job run to its {@link JobQueue}, it * waits for the job to complete and collects the output {@link TaskState}(s) upon completion. * </p> * * <p> * Each {@link WorkUnit} of the job is persisted to the {@link FileSystem} of choice and the path to the file * storing the serialized {@link WorkUnit} is passed to the Helix task running the {@link WorkUnit} as a * user-defined property {@link GobblinClusterConfigurationKeys#WORK_UNIT_FILE_PATH}. Upon startup, the Helix * task reads the property for the file path and de-serializes the {@link WorkUnit} from the file. * </p> * * <p> * This class is instantiated by the {@link GobblinHelixJobScheduler} on every job submission to launch the Gobblin job. * The actual task execution happens in the {@link GobblinTaskRunner}, usually in a different process. * </p> * * @author Yinan Li */ @Alpha @Slf4j public class GobblinHelixJobLauncher extends AbstractJobLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(GobblinHelixJobLauncher.class); private final HelixManager helixManager; private final TaskDriver helixTaskDriver; private final String helixWorkFlowName; private JobListener jobListener; private final FileSystem fs; private final Path appWorkDir; private final Path inputWorkUnitDir; private final Path outputTaskStateDir; // Number of ParallelRunner threads to be used for state serialization/deserialization private final int stateSerDeRunnerThreads; private final TaskStateCollectorService taskStateCollectorService; private final Optional<GobblinHelixMetrics> helixMetrics; private volatile boolean jobSubmitted = false; private final ConcurrentHashMap<String, Boolean> runningMap; private final StateStores stateStores; private final Config jobConfig; private final long workFlowExpiryTimeSeconds; private final long helixJobStopTimeoutSeconds; private final long helixWorkflowSubmissionTimeoutSeconds; private Map<String, TaskConfig> helixIdTaskConfigMap; private Retryer<Boolean> taskRetryer; public GobblinHelixJobLauncher(Properties jobProps, final HelixManager helixManager, Path appWorkDir, List<? extends Tag<?>> metadataTags, ConcurrentHashMap<String, Boolean> runningMap, Optional<GobblinHelixMetrics> helixMetrics) throws Exception { super(jobProps, HelixUtils.initBaseEventTags(jobProps, metadataTags)); LOGGER.debug("GobblinHelixJobLauncher: jobProps {}, appWorkDir {}", jobProps, appWorkDir); this.helixManager = helixManager; this.helixTaskDriver = new TaskDriver(this.helixManager); this.runningMap = runningMap; this.appWorkDir = appWorkDir; this.inputWorkUnitDir = new Path(appWorkDir, GobblinClusterConfigurationKeys.INPUT_WORK_UNIT_DIR_NAME); this.outputTaskStateDir = new Path(this.appWorkDir, GobblinClusterConfigurationKeys.OUTPUT_TASK_STATE_DIR_NAME + Path.SEPARATOR + this.jobContext.getJobId()); this.helixWorkFlowName = this.jobContext.getJobId(); this.jobContext.getJobState().setJobLauncherType(LauncherTypeEnum.CLUSTER); this.stateSerDeRunnerThreads = Integer.parseInt(jobProps.getProperty(ParallelRunner.PARALLEL_RUNNER_THREADS_KEY, Integer.toString(ParallelRunner.DEFAULT_PARALLEL_RUNNER_THREADS))); jobConfig = ConfigUtils.propertiesToConfig(jobProps); this.workFlowExpiryTimeSeconds = ConfigUtils.getLong(jobConfig, GobblinClusterConfigurationKeys.HELIX_WORKFLOW_EXPIRY_TIME_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_WORKFLOW_EXPIRY_TIME_SECONDS); this.helixJobStopTimeoutSeconds = ConfigUtils.getLong(jobConfig, GobblinClusterConfigurationKeys.HELIX_JOB_STOP_TIMEOUT_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_JOB_STOP_TIMEOUT_SECONDS); this.helixWorkflowSubmissionTimeoutSeconds = ConfigUtils.getLong(jobConfig, GobblinClusterConfigurationKeys.HELIX_WORKFLOW_SUBMISSION_TIMEOUT_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_WORKFLOW_SUBMISSION_TIMEOUT_SECONDS); Config stateStoreJobConfig = ConfigUtils.propertiesToConfig(jobProps) .withValue(ConfigurationKeys.STATE_STORE_FS_URI_KEY, ConfigValueFactory.fromAnyRef( new URI(appWorkDir.toUri().getScheme(), null, appWorkDir.toUri().getHost(), appWorkDir.toUri().getPort(), "/", null, null).toString())); this.stateStores = new StateStores(stateStoreJobConfig, appWorkDir, GobblinClusterConfigurationKeys.OUTPUT_TASK_STATE_DIR_NAME, appWorkDir, GobblinClusterConfigurationKeys.INPUT_WORK_UNIT_DIR_NAME, appWorkDir, GobblinClusterConfigurationKeys.JOB_STATE_DIR_NAME); URI fsUri = URI.create(jobProps.getProperty(ConfigurationKeys.FS_URI_KEY, ConfigurationKeys.LOCAL_FS_URI)); this.fs = FileSystem.get(fsUri, new Configuration()); this.taskStateCollectorService = new TaskStateCollectorService(jobProps, this.jobContext.getJobState(), this.eventBus, this.eventSubmitter, this.stateStores.getTaskStateStore(), this.outputTaskStateDir, this.getIssueRepository()); this.helixMetrics = helixMetrics; this.helixIdTaskConfigMap = new HashMap<>(); this.taskRetryer = RetryerBuilder.<Boolean>newBuilder() .retryIfException() .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build(); startCancellationExecutor(); } @Override public void close() throws IOException { try { executeCancellation(); } finally { super.close(); } } public String getJobId() { return this.jobContext.getJobId(); } @Override protected void runWorkUnits(List<WorkUnit> workUnits) throws Exception { try { CountEventBuilder countEventBuilder = new CountEventBuilder(JobEvent.WORK_UNITS_CREATED, workUnits.size()); this.eventSubmitter.submit(countEventBuilder); LOGGER.info("Emitting WorkUnitsCreated Count: " + countEventBuilder.getCount()); long workUnitStartTime = System.currentTimeMillis(); workUnits.forEach((k) -> k.setProp(ConfigurationKeys.WORK_UNIT_CREATION_TIME_IN_MILLIS, workUnitStartTime)); // Start the output TaskState collector service this.taskStateCollectorService.startAsync().awaitRunning(); TimingEvent jobSubmissionTimer = this.eventSubmitter.getTimingEvent(TimingEvent.RunJobTimings.HELIX_JOB_SUBMISSION); synchronized (this.cancellationRequest) { if (!this.cancellationRequested) { long submitStart = System.currentTimeMillis(); if (helixMetrics.isPresent()) { helixMetrics.get().submitMeter.mark(); } submitJobToHelix(createHelixJob(workUnits)); if (helixMetrics.isPresent()) { this.helixMetrics.get().updateTimeForHelixSubmit(submitStart); } jobSubmissionTimer.stop(); LOGGER.info(String.format("Submitted job %s to Helix", this.jobContext.getJobId())); this.jobSubmitted = true; } else { LOGGER.warn("Job {} not submitted to Helix as it was requested to be cancelled.", this.jobContext.getJobId()); } } TimingEvent jobRunTimer = this.eventSubmitter.getTimingEvent(TimingEvent.RunJobTimings.HELIX_JOB_RUN); long waitStart = System.currentTimeMillis(); waitForJobCompletion(); if (helixMetrics.isPresent()) { this.helixMetrics.get().updateTimeForHelixWait(waitStart); } jobRunTimer.stop(); LOGGER.info(String.format("Job %s completed", this.jobContext.getJobId())); } finally { // The last iteration of output TaskState collecting will run when the collector service gets stopped this.taskStateCollectorService.stopAsync().awaitTerminated(); cleanupWorkingDirectory(); } } /** * The implementation of this method has the assumption that work unit change should never delete without adding new * work units, which will cause starvation. Thus, process {@link WorkUnitChangeEvent} for two scenario: * 1. workUnitChangeEvent only contains old tasks and no new tasks given: recalculate new work unit through kafka * source and pack with a min container setting. * 2. workUnitChangeEvent contains both valid old and new work unit: respect the information and directly remove * old tasks and start new work units * * @param workUnitChangeEvent Event post by EventBus to specify old tasks to be removed and new tasks to be run * @throws InvocationTargetException */ @Override @Subscribe public void handleWorkUnitChangeEvent(WorkUnitChangeEvent workUnitChangeEvent) throws InvocationTargetException { log.info("Received WorkUnitChangeEvent with old Task {} and new WU {}", workUnitChangeEvent.getOldTaskIds(), workUnitChangeEvent.getNewWorkUnits()); final JobState jobState = this.jobContext.getJobState(); List<WorkUnit> workUnits = workUnitChangeEvent.getNewWorkUnits(); // Use old task Id to recalculate new work units if(workUnits == null || workUnits.isEmpty()) { workUnits = recalculateWorkUnit(workUnitChangeEvent.getOldTaskIds()); // If no new valid work units can be generated, dismiss the WorkUnitChangeEvent if(workUnits == null || workUnits.isEmpty()) { log.info("Not able to update work unit meaningfully, dismiss the WorkUnitChangeEvent"); return; } } // Follow how AbstractJobLauncher handles work units to make sure consistent behaviour WorkUnitStream workUnitStream = new BasicWorkUnitStream.Builder(workUnits).build(); // For streaming use case, this might be a necessary step to find dataset specific namespace so that each workUnit // can create staging and temp directories with the correct determination of shard-path workUnitStream = this.destDatasetHandlerService.executeHandlers(workUnitStream); workUnitStream = this.processWorkUnitStream(workUnitStream, jobState); workUnits = materializeWorkUnitList(workUnitStream); try { this.removeTasksFromCurrentJob(workUnitChangeEvent.getOldTaskIds()); this.addTasksToCurrentJob(workUnits); } catch (Exception e) { //todo: emit some event to indicate there is an error handling this event that may cause starvation log.error("Failed to process WorkUnitChangeEvent with old tasks {} and new workunits {}.", workUnitChangeEvent.getOldTaskIds(), workUnits, e); throw new InvocationTargetException(e); } } private List<WorkUnit> recalculateWorkUnit(List<String> oldHelixTaskIDs) { JobState jobState = this.jobContext.getJobState(); Map<String, List<Integer>> filteredTopicPartition = new HashMap<>(); for(String id : oldHelixTaskIDs) { WorkUnit workUnit = getWorkUnitFromStateStoreByHelixId(id); String topicName = workUnit.getProp(KafkaSource.TOPIC_NAME); List<Integer> partitions = filteredTopicPartition.getOrDefault(topicName, new LinkedList<>()); partitions.addAll(KafkaUtils.getPartitions(workUnit).stream().map(KafkaPartition::getId).collect(Collectors.toList())); filteredTopicPartition.put(topicName, partitions); } // If a topic contains less than 2 filtered partition, it can't be further split so remove from map filteredTopicPartition.values().removeIf(list -> list == null || list.size() < 2); if(filteredTopicPartition.isEmpty()) { return new ArrayList<>(); } KafkaSource<?, ?> source = (KafkaSource<?, ?>) ((SourceDecorator<?, ?>) this.jobContext.getSource()).getSource(); //TODO: having a smarter way to calculate the new work unit size to replace the current static approach to simply double int newWorkUnitSize = oldHelixTaskIDs.size() * 2; return source.getWorkunitsForFilteredPartitions(jobState, com.google.common.base.Optional.of(filteredTopicPartition), com.google.common.base.Optional.of(newWorkUnitSize)); } @Override protected void executeCancellation() { if (this.jobSubmitted) { try { if (this.cancellationRequested && !this.cancellationExecuted) { boolean cancelByDelete = ConfigUtils.getBoolean(jobConfig, GobblinClusterConfigurationKeys.CANCEL_HELIX_JOB_BY_DELETE, GobblinClusterConfigurationKeys.DEFAULT_CANCEL_HELIX_JOB_BY_DELETE); HelixUtils.cancelWorkflow(this.helixWorkFlowName, this.helixManager, helixJobStopTimeoutSeconds * 1000, cancelByDelete); log.info("Canceled the workflow {}", this.helixWorkFlowName); } } catch (RuntimeException e) { // Cancellation may throw an exception, but Helix set the job state to STOP/DELETE and it should eventually be cleaned up // We will keep this.cancellationExecuted and this.cancellationRequested to true and not propagate the exception log.error("Failed to cancel workflow {} in Helix", helixWorkFlowName, e); } catch (InterruptedException e) { log.error("Thread interrupted while trying to cancel the workflow {} in Helix", helixWorkFlowName); Thread.currentThread().interrupt(); } } } protected void removeTasksFromCurrentJob(List<String> helixTaskIdsToRemove) throws IOException, ExecutionException, RetryException { String jobName = this.jobContext.getJobId(); try (ParallelRunner stateSerDeRunner = new ParallelRunner(this.stateSerDeRunnerThreads, this.fs)) { for (String helixTaskId : helixTaskIdsToRemove) { taskRetryer.call(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String workUnitId = helixIdTaskConfigMap.get(helixTaskId).getConfigMap().get(ConfigurationKeys.TASK_ID_KEY); boolean remove = HelixUtils.deleteTaskFromHelixJob(helixWorkFlowName, jobName, helixTaskId, helixTaskDriver); if (remove) { log.info(String.format("Removed helix task %s with gobblin task id %s from helix job %s:%s ", helixTaskId, workUnitId, helixWorkFlowName, jobName)); } else { throw new IOException( String.format("Cannot remove Helix task %s from helix job %s:%s", helixTaskId, helixWorkFlowName, jobName)); } return true; } }); deleteWorkUnitFromStateStoreByHelixId(helixTaskId, stateSerDeRunner); log.info(String.format("Removed task state for Helix task %s in state store", helixTaskId)); this.helixIdTaskConfigMap.remove(helixTaskId); } } } protected void addTasksToCurrentJob(List<WorkUnit> workUnitsToAdd) throws IOException, ExecutionException, RetryException { String jobName = this.jobContext.getJobId(); try (ParallelRunner stateSerDeRunner = new ParallelRunner(this.stateSerDeRunnerThreads, this.fs)) { for (WorkUnit workunit : workUnitsToAdd) { TaskConfig taskConfig = getTaskConfig(workunit, stateSerDeRunner); this.taskRetryer.call(new Callable<Boolean>() { @Override public Boolean call() throws Exception { boolean added = HelixUtils.addTaskToHelixJob(helixWorkFlowName, jobName, taskConfig, helixTaskDriver); if (added) { log.info( String.format("Added task %s to helix job %s:%s ", workunit.getId(), helixWorkFlowName, jobName)); } else { log.error( String.format("Failed to add task %s to helix job %s:%s ", workunit.getId(), helixWorkFlowName, jobName)); throw new IOException( String.format("Cannot add task %s to helix job %s:%s", workunit.getId(), helixWorkFlowName, jobName)); } return true; } }); } } } /** * Create a job from a given batch of {@link WorkUnit}s. */ JobConfig.Builder createHelixJob(List<WorkUnit> workUnits) throws IOException { Map<String, TaskConfig> taskConfigMap = Maps.newHashMap(); try (ParallelRunner stateSerDeRunner = new ParallelRunner(this.stateSerDeRunnerThreads, this.fs)) { int multiTaskIdSequence = 0; for (WorkUnit workUnit : workUnits) { if (workUnit.isMultiWorkUnit()) { workUnit.setId(JobLauncherUtils.newMultiTaskId(this.jobContext.getJobId(), multiTaskIdSequence++)); } addWorkUnit(workUnit, stateSerDeRunner, taskConfigMap); } Path jobStateFilePath; // write the job.state using the state store if present, otherwise serialize directly to the file if (this.stateStores.haveJobStateStore()) { jobStateFilePath = GobblinClusterUtils.getJobStateFilePath(true, this.appWorkDir, this.jobContext.getJobId()); this.stateStores.getJobStateStore() .put(jobStateFilePath.getParent().getName(), jobStateFilePath.getName(), this.jobContext.getJobState()); } else { jobStateFilePath = GobblinClusterUtils.getJobStateFilePath(false, this.appWorkDir, this.jobContext.getJobId()); SerializationUtils.serializeState(this.fs, jobStateFilePath, this.jobContext.getJobState()); } // Block on persistence of all workunits to be finished. // It is necessary when underlying storage being slow and Helix activate task-execution before the workunit being persisted. stateSerDeRunner.waitForTasks(Long.MAX_VALUE); LOGGER.debug("GobblinHelixJobLauncher.createHelixJob: jobStateFilePath {}, jobState {} jobProperties {}", jobStateFilePath, this.jobContext.getJobState().toString(), this.jobContext.getJobState().getProperties()); return translateGobblinJobConfigToHelixJobConfig(this.jobContext.getJobState(), workUnits, taskConfigMap); } } /** * Populate {@link JobConfig.Builder} with relevant gobblin job-configurations. */ JobConfig.Builder translateGobblinJobConfigToHelixJobConfig(JobState gobblinJobState, List<WorkUnit> workUnits, Map<String, TaskConfig> taskConfigMap) { JobConfig.Builder jobConfigBuilder = new JobConfig.Builder(); // Helix task attempts = retries + 1 (fallback to general task retry for backward compatibility) jobConfigBuilder.setMaxAttemptsPerTask( gobblinJobState.getPropAsInt(GobblinClusterConfigurationKeys.HELIX_TASK_MAX_ATTEMPTS_KEY, gobblinJobState.getPropAsInt(ConfigurationKeys.MAX_TASK_RETRIES_KEY, ConfigurationKeys.DEFAULT_MAX_TASK_RETRIES)) + 1); // Helix task timeout (fallback to general task timeout for backward compatibility) jobConfigBuilder.setTimeoutPerTask( gobblinJobState.getPropAsLong(GobblinClusterConfigurationKeys.HELIX_TASK_TIMEOUT_SECONDS, gobblinJobState.getPropAsLong(ConfigurationKeys.TASK_TIMEOUT_SECONDS, ConfigurationKeys.DEFAULT_TASK_TIMEOUT_SECONDS)) * 1000); jobConfigBuilder.setFailureThreshold(workUnits.size()); jobConfigBuilder.addTaskConfigMap(taskConfigMap).setCommand(GobblinTaskRunner.GOBBLIN_TASK_FACTORY_NAME); jobConfigBuilder.setNumConcurrentTasksPerInstance( ConfigUtils.getInt(jobConfig, GobblinClusterConfigurationKeys.HELIX_CLUSTER_TASK_CONCURRENCY, GobblinClusterConfigurationKeys.HELIX_CLUSTER_TASK_CONCURRENCY_DEFAULT)); if (this.jobConfig.hasPath(GobblinClusterConfigurationKeys.HELIX_JOB_TAG_KEY)) { String jobTag = this.jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_TAG_KEY); log.info("Job {} has tags associated : {}", this.jobContext.getJobId(), jobTag); jobConfigBuilder.setInstanceGroupTag(jobTag); } if (this.jobConfig.hasPath(GobblinClusterConfigurationKeys.HELIX_JOB_TYPE_KEY)) { String jobType = this.jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_TYPE_KEY); log.info("Job {} has types associated : {}", this.jobContext.getJobId(), jobType); jobConfigBuilder.setJobType(jobType); } if (Task.getExecutionModel(ConfigUtils.configToState(jobConfig)).equals(ExecutionModel.STREAMING)) { jobConfigBuilder.setRebalanceRunningTask(true); } jobConfigBuilder.setExpiry( gobblinJobState.getPropAsLong(GobblinClusterConfigurationKeys.HELIX_WORKFLOW_EXPIRY_TIME_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_WORKFLOW_EXPIRY_TIME_SECONDS)); Map<String, String> jobConfigMap = new HashMap<>(); if (this.jobConfig.hasPath(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_MEMORY_MBS)) { jobConfigMap.put(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_MEMORY_MBS, jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_MEMORY_MBS)); log.info("Job {} has specific memory requirement:{}, add this config to command config map", this.jobContext.getJobId(), jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_MEMORY_MBS)); } if (this.jobConfig.hasPath(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_CORES)) { jobConfigMap.put(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_CORES, jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_CORES)); log.info("Job {} has specific Vcore requirement:{}, add this config to command config map", this.jobContext.getJobId(), jobConfig.getString(GobblinClusterConfigurationKeys.HELIX_JOB_CONTAINER_CORES)); } jobConfigBuilder.setJobCommandConfigMap(jobConfigMap); return jobConfigBuilder; } /** * Submit a job to run. */ private void submitJobToHelix(JobConfig.Builder jobConfigBuilder) throws Exception { HelixUtils.submitJobToWorkFlow(jobConfigBuilder, this.helixWorkFlowName, this.jobContext.getJobId(), this.helixTaskDriver, this.helixManager, Duration.ofSeconds(this.workFlowExpiryTimeSeconds), Duration.ofSeconds(this.helixWorkflowSubmissionTimeoutSeconds)); } public void launchJob(@Nullable JobListener jobListener) throws JobException { this.jobListener = jobListener; boolean isLaunched = false; this.runningMap.putIfAbsent(this.jobContext.getJobName(), false); Throwable errorInJobLaunching = null; try { if (this.runningMap.replace(this.jobContext.getJobName(), false, true)) { LOGGER.info("Job {} will be executed, add into running map.", this.jobContext.getJobId()); isLaunched = true; launchJobImpl(jobListener); } else { LOGGER.warn("Job {} will not be executed because other jobs are still running.", this.jobContext.getJobId()); } // TODO: Better error handling. The current impl swallows exceptions for jobs that were started by this method call. // One potential way to improve the error handling is to make this error swallowing configurable } catch (Throwable t) { errorInJobLaunching = t; if (isLaunched) { // Attempts to cancel the helix workflow if an error occurs during launch cancelJob(jobListener); } } finally { if (isLaunched) { if (this.runningMap.replace(this.jobContext.getJobName(), true, false)) { LOGGER.info("Job {} is done, remove from running map.", this.jobContext.getJobId()); } else { throw errorInJobLaunching == null ? new IllegalStateException( "A launched job should have running state equal to true in the running map.") : new RuntimeException("Failure in launching job:", errorInJobLaunching); } } } } /** * This method looks silly at first glance but exists for a reason. * * The method {@link GobblinHelixJobLauncher#launchJob(JobListener)} contains boiler plate for handling exceptions and * mutating the runningMap to communicate state back to the {@link GobblinHelixJobScheduler}. The boiler plate swallows * exceptions when launching the job because many use cases require that 1 job failure should not affect other jobs by causing the * entire process to fail through an uncaught exception. * * This method is useful for unit testing edge cases where we expect {@link JobException}s during the underlying launch operation. * It would be nice to not swallow exceptions, but the implications of doing that will require careful refactoring since * the class {@link GobblinHelixJobLauncher} and {@link GobblinHelixJobScheduler} are shared for 2 quite different cases * between GaaS and streaming. GaaS typically requiring many short lifetime workflows (where a failure is tolerated) and * streaming requiring a small number of long running workflows (where failure to submit is unexpected and is not * tolerated) * * @throws JobException */ @VisibleForTesting void launchJobImpl(@Nullable JobListener jobListener) throws JobException { super.launchJob(jobListener); } private TaskConfig getTaskConfig(WorkUnit workUnit, ParallelRunner stateSerDeRunner) throws IOException { String workUnitFilePath = persistWorkUnit(new Path(this.inputWorkUnitDir, this.jobContext.getJobId()), workUnit, stateSerDeRunner); Map<String, String> rawConfigMap = Maps.newHashMap(); rawConfigMap.put(GobblinClusterConfigurationKeys.WORK_UNIT_FILE_PATH, workUnitFilePath); rawConfigMap.put(ConfigurationKeys.JOB_NAME_KEY, this.jobContext.getJobName()); rawConfigMap.put(ConfigurationKeys.JOB_ID_KEY, this.jobContext.getJobId()); rawConfigMap.put(ConfigurationKeys.TASK_ID_KEY, workUnit.getId()); rawConfigMap.put(GobblinClusterConfigurationKeys.TASK_SUCCESS_OPTIONAL_KEY, "true"); TaskConfig taskConfig = TaskConfig.Builder.from(rawConfigMap); helixIdTaskConfigMap.put(taskConfig.getId(), taskConfig); return taskConfig; } /** * Add a single {@link WorkUnit} (flattened) to persistent storage so that worker can fetch that based on information * fetched in Helix task. */ private void addWorkUnit(WorkUnit workUnit, ParallelRunner stateSerDeRunner, Map<String, TaskConfig> taskConfigMap) throws IOException { taskConfigMap.put(workUnit.getId(), getTaskConfig(workUnit, stateSerDeRunner)); } /** * get a single {@link WorkUnit} (flattened) from state store. */ private WorkUnit getWorkUnitFromStateStoreByHelixId(String helixTaskId) { String workUnitFilePath = helixIdTaskConfigMap.get(helixTaskId).getConfigMap().get(GobblinClusterConfigurationKeys.WORK_UNIT_FILE_PATH); final StateStore stateStore; Path workUnitFile = new Path(workUnitFilePath); String workUnitId = helixIdTaskConfigMap.get(helixTaskId).getConfigMap().get(ConfigurationKeys.TASK_ID_KEY); final String fileName = workUnitFile.getName(); final String storeName = workUnitFile.getParent().getName(); if (fileName.endsWith(MULTI_WORK_UNIT_FILE_EXTENSION)) { stateStore = stateStores.getMwuStateStore(); } else { stateStore = stateStores.getWuStateStore(); } try { return (WorkUnit) stateStore.get(storeName, fileName, workUnitId); } catch (IOException ioException) { log.error("Failed to fetch workUnit for helix task {} from path {}", helixTaskId, workUnitFilePath); } return null; } /** * Delete a single {@link WorkUnit} (flattened) from state store. */ private void deleteWorkUnitFromStateStoreByHelixId(String helixTaskId, ParallelRunner stateSerDeRunner) { String workUnitFilePath = helixIdTaskConfigMap.get(helixTaskId).getConfigMap().get(GobblinClusterConfigurationKeys.WORK_UNIT_FILE_PATH); Path workUnitFile = new Path(workUnitFilePath); final String fileName = workUnitFile.getName(); final String storeName = workUnitFile.getParent().getName(); final StateStore stateStore = JobLauncherUtils.hasMultiWorkUnitExtension(workUnitFile) ? stateStores.getMwuStateStore() : stateStores.getWuStateStore(); stateSerDeRunner.submitCallable(new Callable<Void>() { @Override public Void call() throws Exception { stateStore.delete(storeName, fileName); return null; } }, "Delete state " + fileName + " from store " + storeName); } /** * Persist a single {@link WorkUnit} (flattened) to a file. */ private String persistWorkUnit(final Path workUnitFileDir, final WorkUnit workUnit, ParallelRunner stateSerDeRunner) throws IOException { final StateStore stateStore; String workUnitFileName = workUnit.getId(); if (workUnit.isMultiWorkUnit()) { workUnitFileName += JobLauncherUtils.MULTI_WORK_UNIT_FILE_EXTENSION; stateStore = stateStores.getMwuStateStore(); } else { workUnitFileName += JobLauncherUtils.WORK_UNIT_FILE_EXTENSION; stateStore = stateStores.getWuStateStore(); } Path workUnitFile = new Path(workUnitFileDir, workUnitFileName); final String fileName = workUnitFile.getName(); final String storeName = workUnitFile.getParent().getName(); stateSerDeRunner.submitCallable(new Callable<Void>() { @Override public Void call() throws Exception { stateStore.put(storeName, fileName, workUnit); return null; } }, "Serialize state to store " + storeName + " file " + fileName); return workUnitFile.toString(); } private void waitForJobCompletion() throws InterruptedException { boolean timeoutEnabled = Boolean.parseBoolean( this.jobProps.getProperty(GobblinClusterConfigurationKeys.HELIX_JOB_TIMEOUT_ENABLED_KEY, GobblinClusterConfigurationKeys.DEFAULT_HELIX_JOB_TIMEOUT_ENABLED)); long timeoutInSeconds = Long.parseLong( this.jobProps.getProperty(GobblinClusterConfigurationKeys.HELIX_JOB_TIMEOUT_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_JOB_TIMEOUT_SECONDS)); long stoppingStateTimeoutInSeconds = PropertiesUtils.getPropAsLong(this.jobProps, GobblinClusterConfigurationKeys.HELIX_JOB_STOPPING_STATE_TIMEOUT_SECONDS, GobblinClusterConfigurationKeys.DEFAULT_HELIX_JOB_STOPPING_STATE_TIMEOUT_SECONDS); try { HelixUtils.waitJobCompletion(this.helixManager, this.helixWorkFlowName, this.jobContext.getJobId(), timeoutEnabled ? Optional.of(timeoutInSeconds) : Optional.empty(), stoppingStateTimeoutInSeconds); } catch (TimeoutException te) { HelixUtils.handleJobTimeout(helixWorkFlowName, jobContext.getJobId(), helixManager, this, this.jobListener); } } /** * Delete persisted {@link WorkUnit}s and {@link JobState} upon job completion. */ private void cleanupWorkingDirectory() throws IOException { LOGGER.info("Deleting persisted work units for job " + this.jobContext.getJobId()); stateStores.getWuStateStore().delete(this.jobContext.getJobId()); // delete the directory that stores the task state files stateStores.getTaskStateStore().delete(outputTaskStateDir.getName()); LOGGER.info("Deleting job state file for job " + this.jobContext.getJobId()); if (this.stateStores.haveJobStateStore()) { this.stateStores.getJobStateStore().delete(this.jobContext.getJobId()); } else { Path jobStateFilePath = GobblinClusterUtils.getJobStateFilePath(false, this.appWorkDir, this.jobContext.getJobId()); this.fs.delete(jobStateFilePath, false); } } }
googleapis/google-cloud-java
35,358
java-optimization/proto-google-cloud-optimization-v1/src/main/java/com/google/cloud/optimization/v1/DistanceLimit.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/optimization/v1/fleet_routing.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.optimization.v1; /** * * * <pre> * A limit defining a maximum distance which can be traveled. It can be either * hard or soft. * * If a soft limit is defined, both `soft_max_meters` and * `cost_per_kilometer_above_soft_max` must be defined and be nonnegative. * </pre> * * Protobuf type {@code google.cloud.optimization.v1.DistanceLimit} */ public final class DistanceLimit extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.optimization.v1.DistanceLimit) DistanceLimitOrBuilder { private static final long serialVersionUID = 0L; // Use DistanceLimit.newBuilder() to construct. private DistanceLimit(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DistanceLimit() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DistanceLimit(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.optimization.v1.FleetRoutingProto .internal_static_google_cloud_optimization_v1_DistanceLimit_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.optimization.v1.FleetRoutingProto .internal_static_google_cloud_optimization_v1_DistanceLimit_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.optimization.v1.DistanceLimit.class, com.google.cloud.optimization.v1.DistanceLimit.Builder.class); } private int bitField0_; public static final int MAX_METERS_FIELD_NUMBER = 1; private long maxMeters_ = 0L; /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @return Whether the maxMeters field is set. */ @java.lang.Override public boolean hasMaxMeters() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @return The maxMeters. */ @java.lang.Override public long getMaxMeters() { return maxMeters_; } public static final int SOFT_MAX_METERS_FIELD_NUMBER = 2; private long softMaxMeters_ = 0L; /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @return Whether the softMaxMeters field is set. */ @java.lang.Override public boolean hasSoftMaxMeters() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @return The softMaxMeters. */ @java.lang.Override public long getSoftMaxMeters() { return softMaxMeters_; } public static final int COST_PER_KILOMETER_BELOW_SOFT_MAX_FIELD_NUMBER = 4; private double costPerKilometerBelowSoftMax_ = 0D; /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @return Whether the costPerKilometerBelowSoftMax field is set. */ @java.lang.Override public boolean hasCostPerKilometerBelowSoftMax() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @return The costPerKilometerBelowSoftMax. */ @java.lang.Override public double getCostPerKilometerBelowSoftMax() { return costPerKilometerBelowSoftMax_; } public static final int COST_PER_KILOMETER_ABOVE_SOFT_MAX_FIELD_NUMBER = 3; private double costPerKilometerAboveSoftMax_ = 0D; /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @return Whether the costPerKilometerAboveSoftMax field is set. */ @java.lang.Override public boolean hasCostPerKilometerAboveSoftMax() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @return The costPerKilometerAboveSoftMax. */ @java.lang.Override public double getCostPerKilometerAboveSoftMax() { return costPerKilometerAboveSoftMax_; } 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.writeInt64(1, maxMeters_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(2, softMaxMeters_); } if (((bitField0_ & 0x00000008) != 0)) { output.writeDouble(3, costPerKilometerAboveSoftMax_); } if (((bitField0_ & 0x00000004) != 0)) { output.writeDouble(4, costPerKilometerBelowSoftMax_); } 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.computeInt64Size(1, maxMeters_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(2, softMaxMeters_); } if (((bitField0_ & 0x00000008) != 0)) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(3, costPerKilometerAboveSoftMax_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(4, costPerKilometerBelowSoftMax_); } 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.optimization.v1.DistanceLimit)) { return super.equals(obj); } com.google.cloud.optimization.v1.DistanceLimit other = (com.google.cloud.optimization.v1.DistanceLimit) obj; if (hasMaxMeters() != other.hasMaxMeters()) return false; if (hasMaxMeters()) { if (getMaxMeters() != other.getMaxMeters()) return false; } if (hasSoftMaxMeters() != other.hasSoftMaxMeters()) return false; if (hasSoftMaxMeters()) { if (getSoftMaxMeters() != other.getSoftMaxMeters()) return false; } if (hasCostPerKilometerBelowSoftMax() != other.hasCostPerKilometerBelowSoftMax()) return false; if (hasCostPerKilometerBelowSoftMax()) { if (java.lang.Double.doubleToLongBits(getCostPerKilometerBelowSoftMax()) != java.lang.Double.doubleToLongBits(other.getCostPerKilometerBelowSoftMax())) return false; } if (hasCostPerKilometerAboveSoftMax() != other.hasCostPerKilometerAboveSoftMax()) return false; if (hasCostPerKilometerAboveSoftMax()) { if (java.lang.Double.doubleToLongBits(getCostPerKilometerAboveSoftMax()) != java.lang.Double.doubleToLongBits(other.getCostPerKilometerAboveSoftMax())) 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 (hasMaxMeters()) { hash = (37 * hash) + MAX_METERS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getMaxMeters()); } if (hasSoftMaxMeters()) { hash = (37 * hash) + SOFT_MAX_METERS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSoftMaxMeters()); } if (hasCostPerKilometerBelowSoftMax()) { hash = (37 * hash) + COST_PER_KILOMETER_BELOW_SOFT_MAX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getCostPerKilometerBelowSoftMax())); } if (hasCostPerKilometerAboveSoftMax()) { hash = (37 * hash) + COST_PER_KILOMETER_ABOVE_SOFT_MAX_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getCostPerKilometerAboveSoftMax())); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.optimization.v1.DistanceLimit parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.optimization.v1.DistanceLimit 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.optimization.v1.DistanceLimit parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.optimization.v1.DistanceLimit 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.optimization.v1.DistanceLimit parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.optimization.v1.DistanceLimit parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.optimization.v1.DistanceLimit parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.optimization.v1.DistanceLimit 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.optimization.v1.DistanceLimit parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.optimization.v1.DistanceLimit 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.optimization.v1.DistanceLimit parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.optimization.v1.DistanceLimit 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.optimization.v1.DistanceLimit 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 limit defining a maximum distance which can be traveled. It can be either * hard or soft. * * If a soft limit is defined, both `soft_max_meters` and * `cost_per_kilometer_above_soft_max` must be defined and be nonnegative. * </pre> * * Protobuf type {@code google.cloud.optimization.v1.DistanceLimit} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.optimization.v1.DistanceLimit) com.google.cloud.optimization.v1.DistanceLimitOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.optimization.v1.FleetRoutingProto .internal_static_google_cloud_optimization_v1_DistanceLimit_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.optimization.v1.FleetRoutingProto .internal_static_google_cloud_optimization_v1_DistanceLimit_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.optimization.v1.DistanceLimit.class, com.google.cloud.optimization.v1.DistanceLimit.Builder.class); } // Construct using com.google.cloud.optimization.v1.DistanceLimit.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; maxMeters_ = 0L; softMaxMeters_ = 0L; costPerKilometerBelowSoftMax_ = 0D; costPerKilometerAboveSoftMax_ = 0D; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.optimization.v1.FleetRoutingProto .internal_static_google_cloud_optimization_v1_DistanceLimit_descriptor; } @java.lang.Override public com.google.cloud.optimization.v1.DistanceLimit getDefaultInstanceForType() { return com.google.cloud.optimization.v1.DistanceLimit.getDefaultInstance(); } @java.lang.Override public com.google.cloud.optimization.v1.DistanceLimit build() { com.google.cloud.optimization.v1.DistanceLimit result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.optimization.v1.DistanceLimit buildPartial() { com.google.cloud.optimization.v1.DistanceLimit result = new com.google.cloud.optimization.v1.DistanceLimit(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.optimization.v1.DistanceLimit result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.maxMeters_ = maxMeters_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.softMaxMeters_ = softMaxMeters_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.costPerKilometerBelowSoftMax_ = costPerKilometerBelowSoftMax_; to_bitField0_ |= 0x00000004; } if (((from_bitField0_ & 0x00000008) != 0)) { result.costPerKilometerAboveSoftMax_ = costPerKilometerAboveSoftMax_; to_bitField0_ |= 0x00000008; } 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.optimization.v1.DistanceLimit) { return mergeFrom((com.google.cloud.optimization.v1.DistanceLimit) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.optimization.v1.DistanceLimit other) { if (other == com.google.cloud.optimization.v1.DistanceLimit.getDefaultInstance()) return this; if (other.hasMaxMeters()) { setMaxMeters(other.getMaxMeters()); } if (other.hasSoftMaxMeters()) { setSoftMaxMeters(other.getSoftMaxMeters()); } if (other.hasCostPerKilometerBelowSoftMax()) { setCostPerKilometerBelowSoftMax(other.getCostPerKilometerBelowSoftMax()); } if (other.hasCostPerKilometerAboveSoftMax()) { setCostPerKilometerAboveSoftMax(other.getCostPerKilometerAboveSoftMax()); } 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: { maxMeters_ = input.readInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { softMaxMeters_ = input.readInt64(); bitField0_ |= 0x00000002; break; } // case 16 case 25: { costPerKilometerAboveSoftMax_ = input.readDouble(); bitField0_ |= 0x00000008; break; } // case 25 case 33: { costPerKilometerBelowSoftMax_ = input.readDouble(); bitField0_ |= 0x00000004; break; } // case 33 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 maxMeters_; /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @return Whether the maxMeters field is set. */ @java.lang.Override public boolean hasMaxMeters() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @return The maxMeters. */ @java.lang.Override public long getMaxMeters() { return maxMeters_; } /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @param value The maxMeters to set. * @return This builder for chaining. */ public Builder setMaxMeters(long value) { maxMeters_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * A hard limit constraining the distance to be at most max_meters. The limit * must be nonnegative. * </pre> * * <code>optional int64 max_meters = 1;</code> * * @return This builder for chaining. */ public Builder clearMaxMeters() { bitField0_ = (bitField0_ & ~0x00000001); maxMeters_ = 0L; onChanged(); return this; } private long softMaxMeters_; /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @return Whether the softMaxMeters field is set. */ @java.lang.Override public boolean hasSoftMaxMeters() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @return The softMaxMeters. */ @java.lang.Override public long getSoftMaxMeters() { return softMaxMeters_; } /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @param value The softMaxMeters to set. * @return This builder for chaining. */ public Builder setSoftMaxMeters(long value) { softMaxMeters_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A soft limit not enforcing a maximum distance limit, but when violated * results in a cost which adds up to other costs defined in the model, * with the same unit. * * If defined soft_max_meters must be less than max_meters and must be * nonnegative. * </pre> * * <code>optional int64 soft_max_meters = 2;</code> * * @return This builder for chaining. */ public Builder clearSoftMaxMeters() { bitField0_ = (bitField0_ & ~0x00000002); softMaxMeters_ = 0L; onChanged(); return this; } private double costPerKilometerBelowSoftMax_; /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @return Whether the costPerKilometerBelowSoftMax field is set. */ @java.lang.Override public boolean hasCostPerKilometerBelowSoftMax() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @return The costPerKilometerBelowSoftMax. */ @java.lang.Override public double getCostPerKilometerBelowSoftMax() { return costPerKilometerBelowSoftMax_; } /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @param value The costPerKilometerBelowSoftMax to set. * @return This builder for chaining. */ public Builder setCostPerKilometerBelowSoftMax(double value) { costPerKilometerBelowSoftMax_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Cost per kilometer incurred, increasing up to `soft_max_meters`, with * formula: * ``` * min(distance_meters, soft_max_meters) / 1000.0 * * cost_per_kilometer_below_soft_max. * ``` * This cost is not supported in `route_distance_limit`. * </pre> * * <code>optional double cost_per_kilometer_below_soft_max = 4;</code> * * @return This builder for chaining. */ public Builder clearCostPerKilometerBelowSoftMax() { bitField0_ = (bitField0_ & ~0x00000004); costPerKilometerBelowSoftMax_ = 0D; onChanged(); return this; } private double costPerKilometerAboveSoftMax_; /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @return Whether the costPerKilometerAboveSoftMax field is set. */ @java.lang.Override public boolean hasCostPerKilometerAboveSoftMax() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @return The costPerKilometerAboveSoftMax. */ @java.lang.Override public double getCostPerKilometerAboveSoftMax() { return costPerKilometerAboveSoftMax_; } /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @param value The costPerKilometerAboveSoftMax to set. * @return This builder for chaining. */ public Builder setCostPerKilometerAboveSoftMax(double value) { costPerKilometerAboveSoftMax_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Cost per kilometer incurred if distance is above `soft_max_meters` limit. * The additional cost is 0 if the distance is under the limit, otherwise the * formula used to compute the cost is the following: * ``` * (distance_meters - soft_max_meters) / 1000.0 * * cost_per_kilometer_above_soft_max. * ``` * The cost must be nonnegative. * </pre> * * <code>optional double cost_per_kilometer_above_soft_max = 3;</code> * * @return This builder for chaining. */ public Builder clearCostPerKilometerAboveSoftMax() { bitField0_ = (bitField0_ & ~0x00000008); costPerKilometerAboveSoftMax_ = 0D; 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.optimization.v1.DistanceLimit) } // @@protoc_insertion_point(class_scope:google.cloud.optimization.v1.DistanceLimit) private static final com.google.cloud.optimization.v1.DistanceLimit DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.optimization.v1.DistanceLimit(); } public static com.google.cloud.optimization.v1.DistanceLimit getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DistanceLimit> PARSER = new com.google.protobuf.AbstractParser<DistanceLimit>() { @java.lang.Override public DistanceLimit 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<DistanceLimit> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DistanceLimit> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.optimization.v1.DistanceLimit getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/unomi
35,386
extensions/salesforce-connector/services/src/main/java/org/apache/unomi/sfdc/services/internal/SFDCServiceImpl.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.unomi.sfdc.services.internal; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.unomi.api.Consent; import org.apache.unomi.api.Profile; import org.apache.unomi.persistence.spi.PersistenceService; import org.apache.unomi.sfdc.services.SFDCConfiguration; import org.apache.unomi.sfdc.services.SFDCService; import org.apache.unomi.sfdc.services.SFDCSession; import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.client.ClientSessionChannel; import org.cometd.client.BayeuxClient; import org.cometd.client.http.jetty.JettyHttpClientTransport; import org.cometd.client.transport.ClientTransport; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.util.ajax.JSON; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.util.*; /** * Implementation of the Salesforce connector interface */ public class SFDCServiceImpl implements SFDCService { private static final Logger LOGGER = LoggerFactory.getLogger(SFDCServiceImpl.class.getName()); private static final String REST_ENDPOINT_URI = "/services/data/v38.0"; private static final String STREAMING_ENDPOINT_URI = "/cometd/38.0"; private static final String RESULTSET_KEY_CONTACT = "CONTACT"; private static final String RESULTSET_KEY_LEAD = "LEAD"; private static final int CONNECTION_TIMEOUT = 20 * 1000; // milliseconds private static final int READ_TIMEOUT = 120 * 1000; // milliseconds private SFDCConfiguration sfdcConfiguration; private SFDCConfiguration defaultSFDCConfiguration; private Set<String> sfdcLeadMandatoryFields = new TreeSet<>(); private Set<String> sfdcLeadUpdateableFields = new TreeSet<>(); private SFDCSession sfdcSession; private DateFormat iso8601DateFormat = new ISO8601DateFormat(); private PersistenceService persistenceService; public void setPersistenceService(PersistenceService persistenceService) { this.persistenceService = persistenceService; } public void setDefaultSFDCConfiguration(SFDCConfiguration defaultSFDCConfiguration) { this.defaultSFDCConfiguration = defaultSFDCConfiguration; } public SFDCSession getSFDCSession() { return sfdcSession; } @Override public SFDCConfiguration loadConfiguration() { if (persistenceService == null) { return null; } SFDCConfiguration sfdcConfiguration = persistenceService.load("sfdcConfiguration", SFDCConfiguration.class); return sfdcConfiguration; } @Override public boolean saveConfiguration(SFDCConfiguration sfdcConfiguration) { if (persistenceService == null) { return false; } boolean result = persistenceService.save(sfdcConfiguration); if (result) { this.sfdcConfiguration = sfdcConfiguration; try { if (login(sfdcConfiguration)) { return true; } } catch (HttpException | IOException e) { LOGGER.warn("Error trying to login with new configuration {}", sfdcConfiguration, e); result = false; } } else { LOGGER.error("Error trying to save new Salesforce connection configuration !"); } return result; } public void start() { try { iso8601DateFormat = new ISO8601DateFormat(); SFDCConfiguration sfdcConfiguration = loadConfiguration(); if (sfdcConfiguration != null) { this.sfdcConfiguration = sfdcConfiguration; } else { this.sfdcConfiguration = defaultSFDCConfiguration; } if (this.sfdcConfiguration.isComplete()) { boolean loginSuccessful = login(this.sfdcConfiguration); if (!loginSuccessful) { throw new Exception("Login failed"); } sfdcLeadMandatoryFields = getLeadMandatoryFields(); // setupPushTopics(SFDCSession.getEndPoint(), SFDCSession.getSessionId()); LOGGER.info("Salesforce connector initialized successfully."); } else { LOGGER.warn("Salesforce connector is not yet configured."); } } catch (Exception e) { LOGGER.error("Failed to init SFDCService properly", e); } } public void stop() { } public Set<String> getRecentLeadIds() { if (!isConnected()) { return null; } Set<String> recentLeadIds = new LinkedHashSet<>(); String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead"; HttpGet getRecentLeads = new HttpGet(baseUrl); try { Object responseObject = handleRequest(getRecentLeads); if (responseObject == null) { LOGGER.warn("Couldn't retrieve recent leads"); return null; } Map<String, Object> queryResponse = (Map<String, Object>) responseObject; if (queryResponse.containsKey("recentItems")) { LOGGER.debug("Response received from Salesforce: {}", queryResponse); Object[] recentItems = (Object[]) queryResponse.get("recentItems"); for (Object recentItem : recentItems) { Map<String, String> recentItemMap = (Map<String, String>) recentItem; recentLeadIds.add(recentItemMap.get("Id")); } } } catch (IOException | HttpException e) { LOGGER.error("Error getting recent leads", e); } return recentLeadIds; } public Map<String, Object> getSObject(String sobjectName, String objectId) { if (!isConnected()) { return null; } Map<String, Object> sobjectMap = new LinkedHashMap<>(); String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/" + sobjectName + "/" + objectId; HttpGet getSObject = new HttpGet(baseUrl); try { Object responseObject = handleRequest(getSObject); if (responseObject == null) { LOGGER.warn("Couldn't retrieve sobject {} with id {}", sobjectName, objectId); return null; } Map<String, Object> queryResponse = (Map<String, Object>) responseObject; if (queryResponse != null) { LOGGER.debug("Response received from Salesforce: {}", queryResponse); sobjectMap = new LinkedHashMap<>(queryResponse); } } catch (IOException | HttpException e) { LOGGER.error("Error getting sobject {} with id {}", sobjectName, objectId, e); } return sobjectMap; } public Map<String, Object> getSObjectDescribe(String sobjectName) { Map<String, Object> sobjectDescribe = new LinkedHashMap<>(); if (!isConnected()) { return null; } String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/" + sobjectName + "/describe"; HttpGet getSObjectDescribe = new HttpGet(baseUrl); try { Object responseObject = handleRequest(getSObjectDescribe); if (responseObject == null) { LOGGER.warn("Couldn't retrieve sobject {} describe", sobjectName); return null; } Map<String, Object> queryResponse = (Map<String, Object>) responseObject; if (queryResponse != null) { LOGGER.debug("Response received from Salesforce: {}", queryResponse); sobjectDescribe = new LinkedHashMap<>(queryResponse); } } catch (IOException | HttpException e) { LOGGER.error("Error getting sobject {}", sobjectName, e); } return sobjectDescribe; } public Map<String, Object> getLead(String leadId) { return getSObject("Lead", leadId); } public Set<String> getLeadMandatoryFields() { Set<String> mandatoryFields = new TreeSet<>(); if (!isConnected()) { return null; } Map<String, Object> leadDescribe = getSObjectDescribe("Lead"); Object[] fields = (Object[]) leadDescribe.get("fields"); Set<String> updateableFields = new TreeSet<>(); Set<String> compoundFieldNames = new TreeSet<>(); for (Object field : fields) { Map<String, Object> fieldDescribe = (Map<String, Object>) field; String fieldName = (String) fieldDescribe.get("name"); String compoundFieldName = (String) fieldDescribe.get("compoundFieldName"); if (compoundFieldName != null) { compoundFieldNames.add(compoundFieldName); } String fieldType = (String) fieldDescribe.get("type"); Boolean fieldUpdateable = (Boolean) fieldDescribe.get("updateable"); Boolean fieldCreateable = (Boolean) fieldDescribe.get("createable"); Boolean fieldDefaultedOnCreate = (Boolean) fieldDescribe.get("defaultedOnCreate"); Boolean fieldNillable = (Boolean) fieldDescribe.get("nillable"); if (fieldUpdateable) { updateableFields.add(fieldName); } if (!fieldNillable && !fieldDefaultedOnCreate) { mandatoryFields.add(fieldName); } } mandatoryFields.removeAll(compoundFieldNames); updateableFields.removeAll(compoundFieldNames); sfdcLeadUpdateableFields = updateableFields; return mandatoryFields; } public boolean deleteLead(String leadId) { if (!isConnected()) { return false; } String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead/" + leadId; HttpDelete deleteLead = new HttpDelete(baseUrl); try { Object responseObject = handleRequest(deleteLead); } catch (IOException | HttpException e) { LOGGER.error("Error deleting lead {}", leadId, e); } return true; } private Set<String> mappingResponse(Object response, Set<String> results) { Map<String, Object> result = (Map<String, Object>) response; Long totalSize = (Long) result.get("totalSize"); Boolean done = (Boolean) result.get("done"); Object[] recordObjects = (Object[]) result.get("records"); if (totalSize == null || totalSize < 1) { return results; } for (Object recordObject : recordObjects) { Map<String, Object> record = (Map<String, Object>) recordObject; if (record.containsKey("Id")) { results.add((String) record.get("Id")); } } return results; } public Set<String> findLeadIdsByIdentifierValue(String identifierFieldValue) { Set<String> results = new LinkedHashSet<>(); if (!isConnected()) { return results; } Object response = query("SELECT Id FROM Lead WHERE " + sfdcConfiguration.getSfdcIdentifierField() + "='" + identifierFieldValue + "'"); if (response == null) { return results; } return mappingResponse(response, results); } private boolean isProfileInContacts(String identifierFieldValue) { if (sfdcConfiguration.isSfdcCheckIfContactExistBeforeLeadCreation()) { LOGGER.info("Checking if we have a contact for identifier value {}...", identifierFieldValue); Object response; Set<String> queryResult = new LinkedHashSet<>(); response = query("SELECT Id FROM Contact WHERE " + sfdcConfiguration.getSfdcIdentifierField() + "='" + identifierFieldValue + "'"); queryResult = mappingResponse(response, queryResult); return !queryResult.isEmpty(); } return false; } private void addConsents(Profile profile, Map<String, Object> sfdcLeadFields) { Map<String, Consent> consents = profile.getConsents(); String mappingConsentsString = sfdcConfiguration.getSfdcFieldsConsents(); if (!mappingConsentsString.isEmpty()) { String[] mappingConsents = mappingConsentsString.split(","); for (String mappingConsent : mappingConsents) { String[] mappingConsentArray = mappingConsent.split("<=>"); if (mappingConsentArray.length <= 0) { LOGGER.error("Error with the mapping for field {}, this field will not be mapped please check the cfg file", mappingConsentsString); } else { String consentUnomiId = mappingConsentArray[0]; if (consents.containsKey(consentUnomiId)) { String consentSfdcId = mappingConsentArray[1]; String consentValue = consents.get(consentUnomiId).getStatus().toString(); sfdcLeadFields.put(consentSfdcId, consentValue); LOGGER.debug("Consent {} with value {} was mapped with {}", consentUnomiId, consentValue, consentSfdcId); } else { LOGGER.warn("Consent {} not found in current profile or not answered yet", consentUnomiId); } } } } } @Override public String createOrUpdateLead(Profile profile) { if (!isConnected()) { return null; } // first we must check if an existing contact exists for the profile. String unomiIdentifierValue = (String) profile.getProperty(sfdcConfiguration.getUnomiIdentifierField()); if (isProfileInContacts(unomiIdentifierValue)) { LOGGER.info("Contact {} found in SFDC... No SFDC field value to send, will not send anything to " + "Salesforce. ", unomiIdentifierValue); return null; } // then we must check if an existing lead exists for the profile. LOGGER.info("Checking if we have a lead for identifier value {}...", unomiIdentifierValue); Set<String> foundExistingSfdcLeadIds = findLeadIdsByIdentifierValue(unomiIdentifierValue); Map<String, Object> sfdcLeadFields = new HashMap<>(); Map<String, Object> existingSfdcLeadFields = new HashMap<>(); Date sfdcLastModified = null; if (foundExistingSfdcLeadIds.size() > 1) { // we found multiple leads matching the identifier value ! LOGGER.warn("Found multiple matching leads for identifier value {}, will use first matching one !", unomiIdentifierValue); } if (!foundExistingSfdcLeadIds.isEmpty()) { LOGGER.info("Found an existing lead, attempting to update it..."); // we found an existing lead we must update it existingSfdcLeadFields = getLead(foundExistingSfdcLeadIds.iterator().next()); if (existingSfdcLeadFields.get("LastModifiedDate") != null) { try { sfdcLastModified = iso8601DateFormat.parse((String) existingSfdcLeadFields.get("LastModifiedDate")); } catch (ParseException e) { LOGGER.error("Error parsing date {}", existingSfdcLeadFields.get("LastModifiedDate"), e); } } } else { LOGGER.info("No existing lead found."); } for (String profilePropertyKey : profile.getProperties().keySet()) { String sfdcFieldName = sfdcConfiguration.getUnomiToSfdcFieldMappings().get(profilePropertyKey); if (sfdcFieldName == null) { // we skip unmapped fields continue; } Object unomiPropertyValue = profile.getProperties().get(profilePropertyKey); if (existingSfdcLeadFields.get(sfdcFieldName) == null) { // we only set the field if it didn't have a value. LOGGER.info("Setting SFDC field {} value to {}", sfdcFieldName, unomiPropertyValue); sfdcLeadFields.put(sfdcFieldName, unomiPropertyValue); } else { // current strategy : Unomi field value wins if different from Salesforce value // @todo we should probably improve this by tracking last modification dates on profile/lead properties Object sfdcLeadFieldValue = existingSfdcLeadFields.get(sfdcFieldName); if (!unomiPropertyValue.equals(sfdcLeadFieldValue)) { LOGGER.info("Overwriting SFDC field {} value to {}", sfdcFieldName, unomiPropertyValue); sfdcLeadFields.put(sfdcFieldName, unomiPropertyValue); } } } addConsents(profile, sfdcLeadFields); if (sfdcLeadFields.isEmpty()) { LOGGER.info("No SFDC field value to send, will not send anything to Salesforce."); if (foundExistingSfdcLeadIds.isEmpty()) { return null; } else { return foundExistingSfdcLeadIds.iterator().next(); } } if (existingSfdcLeadFields.isEmpty()) { // if we are creating a lead, let's make sure we have all the mandatory fields before sending the request boolean missingMandatoryFields = false; for (String leadMandatoryFieldName : sfdcLeadMandatoryFields) { if (sfdcLeadFields.get(leadMandatoryFieldName) == null) { LOGGER.warn("Missing mandatory field {}, aborting sending to Salesforce", leadMandatoryFieldName); missingMandatoryFields = true; } } if (missingMandatoryFields) { return null; } } String baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead"; HttpEntityEnclosingRequestBase request = new HttpPost(baseUrl); if (!foundExistingSfdcLeadIds.isEmpty()) { baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/sobjects/Lead/" + foundExistingSfdcLeadIds .iterator().next(); sfdcLeadFields.remove("Id"); request = new HttpPatch(baseUrl); } try { ObjectMapper objectMapper = new ObjectMapper(); StringEntity requestEntity = new StringEntity( objectMapper.writeValueAsString(sfdcLeadFields), ContentType.APPLICATION_JSON); request.setEntity(requestEntity); Object responseObject = handleRequest(request); if (responseObject == null) { return null; } if (responseObject instanceof Map) { Map<String, Object> responseData = (Map<String, Object>) responseObject; if (responseData.get("id") != null) { String sfdcId = (String) responseData.get("id"); LOGGER.info("Lead successfully created/updated in Salesforce. sfdcId={}", sfdcId); return sfdcId; } } LOGGER.info("Response received from Salesforce: {}", responseObject); } catch (IOException | HttpException e) { LOGGER.error("Error creating or updating lead for profile {}", profile, e); } if (foundExistingSfdcLeadIds.isEmpty()) { return null; } else { return foundExistingSfdcLeadIds.iterator().next(); } } @Override public boolean updateProfileFromLead(Profile profile) { if (!isConnected()) { return false; } String unomiIdentifierValue = (String) profile.getProperty(sfdcConfiguration.getUnomiIdentifierField()); Set<String> foundSfdcLeadIds = findLeadIdsByIdentifierValue(unomiIdentifierValue); if (foundSfdcLeadIds.isEmpty()) { LOGGER.info("No lead found in Salesforce corresponding to profile {}", profile); // we didn't find a corresponding lead in salesforce. return false; } else if (foundSfdcLeadIds.size() > 1) { LOGGER.warn("Found multiple leads in Salesforce for identifier value {}, will use first one.", foundSfdcLeadIds); } else { LOGGER.info("Found corresponding lead with identifier value {}", unomiIdentifierValue); } Map<String, Object> sfdcLead = getLead(foundSfdcLeadIds.iterator().next()); if (sfdcLead == null) { LOGGER.error("Error retrieving lead {} from Salesforce", foundSfdcLeadIds); return false; } boolean profileUpdated = false; for (Map.Entry<String, String> sfdcToUnomiFieldMappingEntry : sfdcConfiguration.getSfdcToUnomiFieldMappings() .entrySet()) { String sfdcFieldName = sfdcToUnomiFieldMappingEntry.getKey(); String unomiFieldName = sfdcToUnomiFieldMappingEntry.getValue(); if (sfdcLead.get(sfdcFieldName) != null) { Object sfdcFieldValue = sfdcLead.get(sfdcFieldName); if (sfdcFieldValue != null && !sfdcFieldValue.equals(profile.getProperty(unomiFieldName))) { profile.setProperty(unomiFieldName, sfdcFieldValue); profileUpdated = true; } } } LOGGER.info("Updated profile {} from Salesforce lead {}", profile, sfdcLead); return profileUpdated; } @Override public Map<String, Object> query(String query) { if (!isConnected()) { return null; } // first we must check if an existing lead exists for the profile. String baseUrl = null; try { baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/query?q=" + URLEncoder.encode(query, "UTF-8"); HttpGet get = new HttpGet(baseUrl); Object responseObject = handleRequest(get); if (responseObject instanceof Map) { return (Map<String, Object>) responseObject; } } catch (IOException | HttpException e) { LOGGER.error("Error executing query {}", query, e); } return null; } @Override public Map<String, Object> getLimits() { if (!isConnected()) { return null; } String baseUrl = null; try { baseUrl = sfdcSession.getEndPoint() + REST_ENDPOINT_URI + "/limits"; HttpGet get = new HttpGet(baseUrl); Object responseObject = handleRequest(get); if (responseObject instanceof Map) { return (Map<String, Object>) responseObject; } } catch (IOException | HttpException e) { LOGGER.error("Error retrieving Salesforce API Limits", e); } return null; } private BayeuxClient makeClient() throws Exception { HttpClient httpClient = new HttpClient(new SslContextFactory.Client.Client(true)); httpClient.setConnectTimeout(CONNECTION_TIMEOUT); httpClient.setIdleTimeout(READ_TIMEOUT); httpClient.start(); if (sfdcSession == null) { LOGGER.error("Invalid session !"); return null; } LOGGER.info("Login successful!\nServer URL: {}\nSession ID={}", sfdcSession.getEndPoint(), sfdcSession.getSessionId()); Map<String, Object> options = new HashMap<String, Object>(); options.put(ClientTransport.MAX_NETWORK_DELAY_OPTION, READ_TIMEOUT); JettyHttpClientTransport transport = new JettyHttpClientTransport( options, httpClient) { @Override protected void customize(Request request) { super.customize(request); request.header("Authorization", "OAuth " + sfdcSession.getSessionId()); } }; return new BayeuxClient(getSalesforceStreamingEndpoint( sfdcSession.getEndPoint()), transport); } public void setupPushListener(String channelName, ClientSessionChannel.MessageListener messageListener) throws Exception { if (!isConnected()) { return; } final BayeuxClient client = makeClient(); if (client == null) { throw new Exception("Login failed !"); } client.getChannel(Channel.META_HANDSHAKE).addListener (new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { LOGGER.info("[CHANNEL:META_HANDSHAKE]: {}", message); boolean success = message.isSuccessful(); if (!success) { String error = (String) message.get("error"); if (error != null) { LOGGER.error("Error during HANDSHAKE: {}", error); } Exception exception = (Exception) message.get("exception"); if (exception != null) { LOGGER.error("Exception during HANDSHAKE: ", exception); } } } }); client.getChannel(Channel.META_CONNECT).addListener( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { LOGGER.info("[CHANNEL:META_CONNECT]: {}", message); boolean success = message.isSuccessful(); if (!success) { String error = (String) message.get("error"); if (error != null) { LOGGER.error("Error during CONNECT: {}", error); } } } }); client.getChannel(Channel.META_SUBSCRIBE).addListener( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { LOGGER.debug("[CHANNEL:META_SUBSCRIBE]: {}", message); boolean success = message.isSuccessful(); if (!success) { String error = (String) message.get("error"); if (error != null) { LOGGER.error("Error during SUBSCRIBE: {}", error); } } } }); client.handshake(); LOGGER.debug("Waiting for handshake"); boolean handshaken = client.waitFor(10 * 1000, BayeuxClient.State.CONNECTED); if (!handshaken) { LOGGER.error("Failed to handshake: {}", client); } LOGGER.info("Subscribing for channel: {}", channelName); client.getChannel(channelName).subscribe(messageListener); } private String getSalesforceStreamingEndpoint(String endpoint) throws MalformedURLException { return new URL(endpoint + STREAMING_ENDPOINT_URI).toExternalForm(); } private void setupPushTopics(String host, String sessionId) throws HttpException, IOException { String baseUrl = host + REST_ENDPOINT_URI + "/query?q=" + URLEncoder.encode("SELECT Id from PushTopic WHERE " + "name = 'LeadUpdates'", "UTF-8"); HttpGet get = new HttpGet(baseUrl); Map<String, String> queryResponse = (Map<String, String>) handleRequest(get); if (queryResponse != null && queryResponse.containsKey("count")) { LOGGER.info("Push topics setup successfully"); } } public boolean login(SFDCConfiguration sfdcConfiguration) throws HttpException, IOException { String baseUrl = sfdcConfiguration.getSfdcLoginEndpoint() + "/services/oauth2/token"; HttpPost oauthPost = new HttpPost(baseUrl); List<BasicNameValuePair> parametersBody = new ArrayList<>(); parametersBody.add(new BasicNameValuePair("grant_type", "password")); parametersBody.add(new BasicNameValuePair("username", sfdcConfiguration.getSfdcUserUsername())); parametersBody.add(new BasicNameValuePair("password", sfdcConfiguration.getSfdcUserPassword() + sfdcConfiguration.getSfdcUserSecurityToken())); parametersBody.add(new BasicNameValuePair("client_id", sfdcConfiguration.getSfdcConsumerKey())); parametersBody.add(new BasicNameValuePair("client_secret", sfdcConfiguration.getSfdcConsumerSecret())); oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, "UTF-8")); Map<String, String> oauthLoginResponse = (Map<String, String>) handleRequest(oauthPost, 0, false); if (oauthLoginResponse == null) { return false; } sfdcSession = new SFDCSession( oauthLoginResponse.get("access_token"), oauthLoginResponse.get("instance_url"), oauthLoginResponse.get("signature"), oauthLoginResponse.get("id"), oauthLoginResponse.get("token_type"), oauthLoginResponse.get("issued_at"), sfdcConfiguration.getSfdcSessionTimeout()); return true; } public void logout() { sfdcSession = null; } private SFDCSession getValidSession() { if (isSessionValid()) { return sfdcSession; } boolean loginSuccessful = false; try { loginSuccessful = login(sfdcConfiguration); if (loginSuccessful && sfdcSession != null) { return sfdcSession; } } catch (HttpException | IOException e) { LOGGER.error("Error logging in", e); return null; } return null; } private boolean isSessionValid() { if (sfdcSession == null) { return false; } return !sfdcSession.isExpired(); } private Object handleRequest(HttpUriRequest request) throws IOException, HttpException { return handleRequest(request, 1, true); } private Object handleRequest(HttpUriRequest request, int retryCount, boolean addAuthorizationHeader) throws IOException, HttpException { CloseableHttpClient client = HttpClientBuilder.create().build(); if (addAuthorizationHeader) { SFDCSession sfdcSession = getValidSession(); if (sfdcSession == null) { LOGGER.error("Couldn't get a valid session !"); return null; } if (request.containsHeader("Authorization")) { LOGGER.debug("Replacing existing authorization header with an updated one."); Header[] authorizationHeaders = request.getHeaders("Authorization"); for (Header authorizationHeader : authorizationHeaders) { request.removeHeader(authorizationHeader); } } request.addHeader("Authorization", "Bearer " + sfdcSession.getSessionId()); } CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() >= 400) { if ((response.getStatusLine().getStatusCode() == 401 || response.getStatusLine().getStatusCode() == 403) && retryCount > 0) { // probably the session has expired, let's try to login again LOGGER.warn("Unauthorized request, attempting to login again..."); boolean loginSuccessful = login(sfdcConfiguration); if (!loginSuccessful) { LOGGER.error("Login failed, cannot execute request {}", request); return null; } LOGGER.warn("Retrying request {} once again...", request); return handleRequest(request, 0, true); } else { LOGGER.error("Error executing request {}: {}-{}", request, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); if (response.getEntity() != null) { LOGGER.error("Entity={}", EntityUtils.toString(response.getEntity())); } } return null; } if (response.getEntity() == null) { return null; } return JSON.parse(EntityUtils.toString(response.getEntity())); } public boolean isConfigured() { if (!sfdcConfiguration.isComplete()) { LOGGER.warn("Connection to Salesforce is not properly configured !"); return false; } return true; } public boolean isConnected() { if (!isConfigured()) { return false; } if (sfdcSession == null) { LOGGER.warn("Not connected to SalesForce, operation will not execute."); return false; } else { if (sfdcSession.isExpired()) { LOGGER.warn("Connection to Salesforce has expired, will reconnect on next request"); return true; } } return true; } }
google/cel-java
35,556
checker/src/main/java/dev/cel/checker/Env.java
// Copyright 2023 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 dev.cel.checker; import dev.cel.expr.Constant; import dev.cel.expr.Decl; import dev.cel.expr.Decl.FunctionDecl.Overload; import dev.cel.expr.Expr; import dev.cel.expr.Type; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; import dev.cel.checker.CelStandardDeclarations.StandardFunction.Overload.Comparison; import dev.cel.checker.CelStandardDeclarations.StandardFunction.Overload.Conversions; import dev.cel.common.CelContainer; import dev.cel.common.CelFunctionDecl; import dev.cel.common.CelOptions; import dev.cel.common.CelOverloadDecl; import dev.cel.common.annotations.Internal; import dev.cel.common.ast.CelConstant; import dev.cel.common.ast.CelExpr; import dev.cel.common.ast.CelExprConverter; import dev.cel.common.ast.CelReference; import dev.cel.common.internal.Errors; import dev.cel.common.types.CelKind; import dev.cel.common.types.CelProtoTypes; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypes; import dev.cel.common.types.SimpleType; import dev.cel.parser.CelStandardMacro; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.jspecify.annotations.Nullable; /** * Environment used during checking of expressions. Provides name resolution and error reporting. * * <p>Note: the environment is not thread-safe. Create multiple envs from scratch for working with * different threads. * * <p>CEL Library Internals. Do Not Use. CEL-Java users should leverage the Fluent APIs instead. See * {@code CelCompilerFactory}. */ @Internal public class Env { /** The top-most scope in the environment, for use with {@link #getDeclGroup(int)}. */ public static final int ROOT_SCOPE = 0; /** An ident declaration to represent an error. */ public static final CelIdentDecl ERROR_IDENT_DECL = CelIdentDecl.newBuilder().setName("*error*").setType(SimpleType.ERROR).build(); /** A function declaration to represent an error. */ public static final CelFunctionDecl ERROR_FUNCTION_DECL = CelFunctionDecl.newBuilder().setName("*error*").build(); /** Type provider responsible for resolving CEL message references to strong types. */ private final TypeProvider typeProvider; /** * Stack of declaration groups where each entry in stack represents a scope capable of hinding * declarations lower in the stack. */ private final ArrayList<DeclGroup> decls = new ArrayList<>(); /** A map from expression ids into references resolved for the overall tree so far. */ private final Map<Long, CelReference> referenceMap = new LinkedHashMap<>(); /** A map from expression ids into types resolved for the overall tree so far. */ private final Map<Long, CelType> typeMap = new LinkedHashMap<>(); /** Object used for error reporting. */ private final Errors errors; /** CEL Feature flags. */ private final CelOptions celOptions; private static final CelOptions LEGACY_TYPE_CHECKER_OPTIONS = CelOptions.newBuilder() .disableCelStandardEquality(false) .enableNamespacedDeclarations(false) .build(); private Env( Errors errors, TypeProvider typeProvider, DeclGroup declGroup, CelOptions celOptions) { this.celOptions = celOptions; this.errors = Preconditions.checkNotNull(errors); this.typeProvider = Preconditions.checkNotNull(typeProvider); this.decls.add(Preconditions.checkNotNull(declGroup)); } /** * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. */ @Deprecated public static Env unconfigured(Errors errors) { return unconfigured(errors, LEGACY_TYPE_CHECKER_OPTIONS); } /** * Creates an unconfigured {@code Env} value without the standard CEL types, functions, and * operators with a reference to the configured {@code celOptions}. */ @VisibleForTesting static Env unconfigured(Errors errors, CelOptions celOptions) { return unconfigured(errors, new DescriptorTypeProvider(), celOptions); } /** * Creates an unconfigured {@code Env} value without the standard CEL types, functions, and * operators using a custom {@code typeProvider}. * * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. */ @Deprecated public static Env unconfigured(Errors errors, TypeProvider typeProvider, CelOptions celOptions) { return new Env(errors, typeProvider, new DeclGroup(), celOptions); } /** * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. */ @Deprecated public static Env standard(Errors errors) { return standard(errors, new DescriptorTypeProvider()); } /** * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. */ @Deprecated public static Env standard(Errors errors, TypeProvider typeProvider) { return standard(errors, typeProvider, LEGACY_TYPE_CHECKER_OPTIONS); } /** * Creates an {@code Env} value configured with the standard types, functions, and operators, * configured with a custom {@code typeProvider} and a reference to the {@code celOptions} to use * within the environment. * * <p>Note: standard declarations are configured in an isolated scope, and may be shadowed by * subsequent declarations with the same signature. * * @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs. * See {@code CelCompilerFactory}. */ @Deprecated public static Env standard(Errors errors, TypeProvider typeProvider, CelOptions celOptions) { CelStandardDeclarations celStandardDeclaration = CelStandardDeclarations.newBuilder() .filterFunctions( (function, overload) -> { switch (function) { case INT: if (!celOptions.enableUnsignedLongs() && overload.equals(Conversions.INT64_TO_INT64)) { return false; } break; case TIMESTAMP: // TODO: Remove this flag guard once the feature has been // auto-enabled. if (!celOptions.enableTimestampEpoch() && overload.equals(Conversions.INT64_TO_TIMESTAMP)) { return false; } break; default: if (!celOptions.enableHeterogeneousNumericComparisons() && overload instanceof Comparison) { Comparison comparison = (Comparison) overload; if (comparison.isHeterogeneousComparison()) { return false; } } break; } return true; }) .build(); return standard(celStandardDeclaration, errors, typeProvider, celOptions); } public static Env standard( CelStandardDeclarations celStandardDeclaration, Errors errors, TypeProvider typeProvider, CelOptions celOptions) { Env env = Env.unconfigured(errors, typeProvider, celOptions); // Isolate the standard declarations into their own scope for forward compatibility. celStandardDeclaration.functionDecls().forEach(env::add); celStandardDeclaration.identifierDecls().forEach(env::add); env.enterScope(); return env; } /** Returns the current Errors object. */ public Errors getErrorContext() { return errors; } /** Returns the {@code TypeProvider}. */ public TypeProvider getTypeProvider() { return typeProvider; } /** * Enters a new scope. All new declarations added to the environment exist only in this scope, and * will shadow declarations of the same name in outer scopes. This includes overloads in outer * scope (overloads from different scopes are not merged). */ public void enterScope() { decls.add(new DeclGroup()); } /** Exits a previously opened scope, forgetting all declarations created in this scope. */ public void exitScope() { Preconditions.checkState(!decls.isEmpty(), "Cannot exit top-level environment scope"); decls.remove(decls.size() - 1); } /** Return the current scope depth for the environment. */ public int scopeDepth() { return decls.size() - 1; } /** Returns the top-most declaration scope. */ public DeclGroup getDeclGroup() { return Iterables.getLast(decls); } /** * Returns the {@code DeclGroup} at the given {@code scopeDepth}, where depth of {@code 0} * represents root scope. */ public DeclGroup getDeclGroup(int scopeDepth) { Preconditions.checkArgument( scopeDepth <= scopeDepth() && scopeDepth >= 0, "Invalid scope depth."); return decls.get(scopeDepth); } /** Reset type and ref maps. This must be called before type checking an expression. */ public void resetTypeAndRefMaps() { typeMap.clear(); referenceMap.clear(); } /** Returns the reference map. */ public Map<Long, CelReference> getRefMap() { return referenceMap; } /** Returns the type map. */ public Map<Long, CelType> getTypeMap() { return typeMap; } /** * Returns the type associated with an expression by expression id. It's an error to call this * method if the type is not present. * * @deprecated Use {@link #getType(CelExpr)} instead. */ @Deprecated public Type getType(Expr expr) { Preconditions.checkNotNull(expr); return CelProtoTypes.celTypeToType(getType(CelExprConverter.fromExpr(expr))); } /** * Returns the type associated with an expression by expression id. It's an error to call this * method if the type is not present. */ public CelType getType(CelExpr expr) { return Preconditions.checkNotNull(typeMap.get(expr.id()), "expression has no type"); } /** * Sets the type associated with an expression by id. It's an error if the type is already set and * is different than the provided one. Returns the expression parameter. */ @CanIgnoreReturnValue public CelExpr setType(CelExpr expr, CelType type) { CelType oldType = typeMap.put(expr.id(), type); Preconditions.checkState( oldType == null || oldType.equals(type), "expression already has a type which is incompatible.\n old: %s\n new: %s", oldType, type); return expr; } /** * Sets the reference associated with an expression. It's an error if the reference is already set * and is different. */ public void setRef(CelExpr expr, CelReference reference) { CelReference oldReference = referenceMap.put(expr.id(), reference); Preconditions.checkState( oldReference == null || oldReference.equals(reference), "expression already has a reference which is incompatible"); } /** * Adds a declaration to the environment, based on the Decl proto. Will report errors if the * declaration overlaps with an existing one, or clashes with a macro. * * @deprecated Migrate to the CEL-Java fluent APIs and leverage the publicly available native * types (e.g: {@code CelCompilerFactory} accepts {@code CelFunctionDecl} and {@code * CelVarDecl}). */ @CanIgnoreReturnValue @Deprecated public Env add(Decl decl) { switch (decl.getDeclKindCase()) { case IDENT: CelIdentDecl.Builder identBuilder = CelIdentDecl.newBuilder() .setName(decl.getName()) .setType(CelProtoTypes.typeToCelType(decl.getIdent().getType())) // Note: Setting doc and constant value exists for compatibility reason. This should // not be set by the users. .setDoc(decl.getIdent().getDoc()); if (decl.getIdent().hasValue()) { identBuilder.setConstant( CelExprConverter.exprConstantToCelConstant(decl.getIdent().getValue())); } return add(identBuilder.build()); case FUNCTION: ImmutableList.Builder<CelOverloadDecl> overloadDeclBuilder = new ImmutableList.Builder<>(); for (Overload overload : decl.getFunction().getOverloadsList()) { overloadDeclBuilder.add(CelOverloadDecl.overloadToCelOverload(overload)); } return add( CelFunctionDecl.newBuilder() .setName(decl.getName()) .addOverloads(overloadDeclBuilder.build()) .build()); default: break; } return this; } @CanIgnoreReturnValue public Env add(CelFunctionDecl celFunctionDecl) { return addFunction(sanitizeFunction(celFunctionDecl)); } @CanIgnoreReturnValue public Env add(CelIdentDecl celIdentDecl) { return addIdent(sanitizeIdent(celIdentDecl)); } /** * Adds simple name declaration to the environment for a non-function. * * @deprecated Migrate to the CEL-Java fluent APIs and leverage the publicly available native * types (e.g: {@code CelCompilerFactory} accepts {@code CelFunctionDecl} and {@code * CelVarDecl}). */ @CanIgnoreReturnValue @Deprecated public Env add(String name, Type type) { return add(CelIdentDecl.newIdentDeclaration(name, CelProtoTypes.typeToCelType(type))); } /** * Note: Used by legacy type-checker users * * @deprecated Use {@link #tryLookupCelFunction} instead. */ @Deprecated public @Nullable Decl tryLookupFunction(String container, String name) { CelFunctionDecl decl = tryLookupCelFunction(CelContainer.ofName(container), name); if (decl == null) { return null; } return CelFunctionDecl.celFunctionDeclToDecl(decl); } /** * Try to lookup a function with the given {@code name} within a {@code container}. * * <p>For protos, the {@code container} may be a package or message name. The code tries to * resolve the {@code name} first in the container, then within the container parent, and so on * until the root package is reached. If {@code container} starts with {@code .}, the resolution * is in the root container only. * * <p>Returns {@code null} if the function cannot be found. */ public @Nullable CelFunctionDecl tryLookupCelFunction(CelContainer container, String name) { for (String cand : container.resolveCandidateNames(name)) { // First determine whether we know this name already. CelFunctionDecl decl = findFunctionDecl(cand); if (decl != null) { return decl; } } return null; } /** * @deprecated Use {@link #tryLookupCelIdent} instead. */ @Deprecated public @Nullable Decl tryLookupIdent(CelContainer container, String name) { CelIdentDecl decl = tryLookupCelIdent(container, name); if (decl == null) { return null; } return CelIdentDecl.celIdentToDecl(decl); } /** * Try to lookup an identifier with the given {@code name} within a {@code container}. * * <p>For protos, the {@code container} may be a package or message name. The code tries to * resolve the {@code name} first in the container, then within the container parent, and so on * until the root package is reached. If {@code container} starts with {@code .}, the resolution * is in the root container only. * * <p>Returns {@code null} if the function cannot be found. */ public @Nullable CelIdentDecl tryLookupCelIdent(CelContainer container, String name) { for (String cand : container.resolveCandidateNames(name)) { // First determine whether we know this name already. CelIdentDecl decl = findIdentDecl(cand); if (decl != null) { return decl; } // Next try to import the name as a reference to a message type. // This is done via the type provider. Optional<CelType> type = typeProvider.lookupCelType(cand); if (type.isPresent()) { decl = CelIdentDecl.newIdentDeclaration(cand, type.get()); decls.get(0).putIdent(decl); return decl; } // Next try to import this as an enum value by splitting the name in a type prefix and // the enum inside. Integer enumValue = typeProvider.lookupEnumValue(cand); if (enumValue != null) { decl = CelIdentDecl.newBuilder() .setName(cand) .setType(SimpleType.INT) .setConstant(CelConstant.ofValue(enumValue)) .build(); decls.get(0).putIdent(decl); return decl; } } return null; } /** * Lookup a name like {@link #tryLookupCelIdent}, but report an error if the name is not found and * return the {@link #ERROR_IDENT_DECL}. */ public CelIdentDecl lookupIdent(long exprId, int position, CelContainer container, String name) { CelIdentDecl result = tryLookupCelIdent(container, name); if (result == null) { reportError( exprId, position, "undeclared reference to '%s' (in container '%s')", name, container.name()); return ERROR_IDENT_DECL; } return result; } /** * Lookup a name like {@link #tryLookupCelFunction} but report an error if the name is not found * and return the {@link #ERROR_FUNCTION_DECL}. */ public CelFunctionDecl lookupFunction( long exprId, int position, CelContainer container, String name) { CelFunctionDecl result = tryLookupCelFunction(container, name); if (result == null) { reportError( exprId, position, "undeclared reference to '%s' (in container '%s')", name, container.name()); return ERROR_FUNCTION_DECL; } return result; } /** * Note: Used by legacy type-checker users * * @deprecated Use {@link #reportError(long, int, String, Object...) instead.} */ @Deprecated public void reportError(int position, String message, Object... args) { reportError(0L, position, message, args); } /** Reports an error. */ public void reportError(long exprId, int position, String message, Object... args) { errors.reportError(exprId, position, message, args); } boolean enableCompileTimeOverloadResolution() { return celOptions.enableCompileTimeOverloadResolution(); } boolean enableHomogeneousLiterals() { return celOptions.enableHomogeneousLiterals(); } boolean enableNamespacedDeclarations() { return celOptions.enableNamespacedDeclarations(); } /** Add an identifier {@code decl} to the environment. */ @CanIgnoreReturnValue private Env addIdent(CelIdentDecl celIdentDecl) { CelIdentDecl current = getDeclGroup().getIdent(celIdentDecl.name()); if (current == null) { getDeclGroup().putIdent(celIdentDecl); } else { reportError( /* exprId= */ 0, /* position= */ 0, "overlapping declaration name '%s' (type '%s' cannot be distinguished from '%s')", celIdentDecl.name(), CelTypes.format(current.type()), CelTypes.format(celIdentDecl.type())); } return this; } /** Add a function {@code decl} to the environment. */ @CanIgnoreReturnValue private Env addFunction(CelFunctionDecl decl) { CelFunctionDecl current = getDeclGroup().getFunction(decl.name()); CelFunctionDecl.Builder builder = current != null ? current.toBuilder() : CelFunctionDecl.newBuilder().setName(decl.name()); for (CelOverloadDecl overload : decl.overloads()) { addOverload(builder, overload); } getDeclGroup().putFunction(builder.build()); return this; } /** * Attempt to extend the declaration with a new overload. This reports an error if the overload * overlaps with existing ones or with a macro. */ private void addOverload(CelFunctionDecl.Builder builder, CelOverloadDecl overload) { // Compute the type of the overload with all type parameters replaced by DYN. // We are using a property of Types.substitute which replaces all unbound type // parameters by DYN. ImmutableMap<CelType, CelType> emptySubs = ImmutableMap.of(); CelType overloadFunction = CelTypes.createFunctionType(overload.resultType(), overload.parameterTypes()); CelType overloadTypeErased = Types.substitute(emptySubs, overloadFunction, true); // Loop over existing overloads to find any overlap. for (CelOverloadDecl existing : builder.overloads()) { CelType existingFunction = CelTypes.createFunctionType(existing.resultType(), existing.parameterTypes()); CelType existingTypeErased = Types.substitute(emptySubs, existingFunction, true); boolean overlap = Types.isAssignable(emptySubs, overloadTypeErased, existingTypeErased) != null || Types.isAssignable(emptySubs, existingTypeErased, overloadTypeErased) != null; if (overlap && existing.isInstanceFunction() == overload.isInstanceFunction()) { reportError( /* exprId= */ 0, /* position= */ 0, "overlapping overload for name '%s' (type '%s' cannot be distinguished from '%s')", builder.name(), CelTypes.format(existingFunction), CelTypes.format(overloadFunction)); return; } } // If this is a function, loop over macros to detect any clash. for (CelStandardMacro macro : CelStandardMacro.STANDARD_MACROS) { if (macro.getFunction().equals(builder.name()) && macro.getDefinition().isReceiverStyle() == overload.isInstanceFunction() && macro.getDefinition().getArgumentCount() == overload.parameterTypes().size()) { reportError( /* exprId= */ 0, /* position= */ 0, "overload for name '%s' with %s argument(s) overlaps with predefined macro", builder.name(), macro.getDefinition().getArgumentCount()); return; } } builder.addOverloads(overload); } /** Search for the named identifier declaration. */ private @Nullable CelIdentDecl findIdentDecl(String name) { for (DeclGroup declGroup : Lists.reverse(decls)) { CelIdentDecl ident = declGroup.getIdent(name); if (ident != null) { return ident; } } return null; } /** Search for the named function declaration. */ private @Nullable CelFunctionDecl findFunctionDecl(String name) { // Search bottom-up for the matching function declarations. List<CelFunctionDecl> functions = new ArrayList<>(); for (DeclGroup declGroup : Lists.reverse(decls)) { CelFunctionDecl function = declGroup.getFunction(name); if (function != null) { functions.add(function); } } // If no functions have the declared name, return null. if (functions.isEmpty()) { return null; } // If only one function declaration has the specified name, return it. if (functions.size() == 1) { return functions.get(0); } // Otherwise form a composite view of the overloads, most specific first, as indicated by the // bottom-up traversal order of the declaration scopes. Map<String, CelOverloadDecl> overloadSignatureMap = new HashMap<>(); for (CelFunctionDecl function : functions) { for (CelOverloadDecl overload : function.overloads()) { // The input signature is enough to disambiguate overloads. When two or more functions in // different scopes share the same signature, the function in the lowest scope will shadow // its ancestors. // // Note: declaring a function with the same signature in the same scope is an error. String overloadSignature = TypeFormatter.formatFunction( /* resultType= */ null, overload.parameterTypes(), overload.isInstanceFunction(), /* typeParamToDyn= */ true); overloadSignatureMap.putIfAbsent(overloadSignature, overload); } } return CelFunctionDecl.newBuilder() .setName(name) .addOverloads(overloadSignatureMap.values()) .build(); } /** * A helper class for constructing identifier declarations. * * @deprecated Use {@code CelVarDecl#newBuilder()} instead. */ @Deprecated public static final class IdentBuilder { private final CelIdentDecl.Builder builder = CelIdentDecl.newBuilder(); /** Create an identifier builder. */ public IdentBuilder(String name) { builder.setName(Preconditions.checkNotNull(name)); } /** Set the identifier type. */ @CanIgnoreReturnValue public IdentBuilder type(Type value) { Preconditions.checkNotNull(value); builder.setType(CelProtoTypes.typeToCelType(Preconditions.checkNotNull(value))); return this; } /** Set the identifier to a {@code Constant} value. */ @CanIgnoreReturnValue public IdentBuilder value(@Nullable Constant value) { if (value == null) { builder.clearConstant(); } else { builder.setConstant(CelExprConverter.exprConstantToCelConstant(value)); } return this; } /** Set the documentation for the identifier. */ @CanIgnoreReturnValue public IdentBuilder doc(@Nullable String value) { if (value == null) { builder.setDoc(""); } else { builder.setDoc(value); } return this; } /** Build the ident {@code Decl}. */ public Decl build() { return CelIdentDecl.celIdentToDecl(builder.build()); } } /** * A helper class for building declarations. * * @deprecated Use {@link CelFunctionDecl#newBuilder()} instead. */ @Deprecated public static final class FunctionBuilder { private final String name; private final List<CelOverloadDecl> overloads = new ArrayList<>(); private final boolean isInstance; /** Create a global function builder. */ public FunctionBuilder(String name) { this(name, false); } /** Create an instance function builder. */ public FunctionBuilder(String name, boolean isInstance) { this.name = Preconditions.checkNotNull(name); this.isInstance = isInstance; } /** * Add the overloads of another function to this function, after replacing the overload id as * specified. */ @CanIgnoreReturnValue public FunctionBuilder sameAs(Decl func, String idPart, String idPartReplace) { Preconditions.checkNotNull(func); for (Overload overload : func.getFunction().getOverloadsList()) { this.overloads.add( CelOverloadDecl.overloadToCelOverload(overload).toBuilder() .setOverloadId(overload.getOverloadId().replace(idPart, idPartReplace)) .build()); } return this; } /** Add an overload. */ @CanIgnoreReturnValue public FunctionBuilder add(String id, Type resultType, Type... argTypes) { return add(id, resultType, ImmutableList.copyOf(argTypes)); } /** Add an overload. */ @CanIgnoreReturnValue public FunctionBuilder add(String id, Type resultType, Iterable<Type> argTypes) { ImmutableList.Builder<CelType> argumentBuilder = new ImmutableList.Builder<>(); for (Type type : argTypes) { argumentBuilder.add(CelProtoTypes.typeToCelType(type)); } this.overloads.add( CelOverloadDecl.newBuilder() .setOverloadId(id) .setResultType(CelProtoTypes.typeToCelType(resultType)) .addParameterTypes(argumentBuilder.build()) .setIsInstanceFunction(isInstance) .build()); return this; } /** Add an overload, with type params. */ @CanIgnoreReturnValue public FunctionBuilder add( String id, List<String> typeParams, Type resultType, Type... argTypes) { return add(id, typeParams, resultType, ImmutableList.copyOf(argTypes)); } /** Add an overload, with type params. */ @CanIgnoreReturnValue public FunctionBuilder add( String id, List<String> typeParams, Type resultType, Iterable<Type> argTypes) { ImmutableList.Builder<CelType> argumentBuilder = new ImmutableList.Builder<>(); for (Type type : argTypes) { argumentBuilder.add(CelProtoTypes.typeToCelType(type)); } this.overloads.add( CelOverloadDecl.newBuilder() .setOverloadId(id) .setResultType(CelProtoTypes.typeToCelType(resultType)) .addParameterTypes(argumentBuilder.build()) .setIsInstanceFunction(isInstance) .build()); return this; } /** Adds documentation to the last added overload. */ @CanIgnoreReturnValue public FunctionBuilder doc(@Nullable String value) { int current = this.overloads.size() - 1; CelOverloadDecl.Builder builder = this.overloads.get(current).toBuilder(); if (value == null) { builder.setDoc(""); } else { builder.setDoc(value); } this.overloads.set(current, builder.build()); return this; } /** Build the function {@code Decl}. */ @CheckReturnValue public Decl build() { return CelFunctionDecl.celFunctionDeclToDecl( CelFunctionDecl.newBuilder().setName(name).addOverloads(overloads).build()); } } /** * Object for managing a group of declarations within a scope. * * <p>Identifiers and functions can share the same declaration name, so a simple map will not * suffice for tracking declaration overloads. * * <p>Whether a given {@code DeclGroup} is mutable or immutable depends on whether the maps * supplied as input to the group are standard {@code Map} implementations or {@code ImmutableMap} * implementations. The {DeclGroup#immutableCopy} method is provided as a convenience to make it * easy to create an instance of the group which will honor the developer's intent. */ public static class DeclGroup { private final Map<String, CelIdentDecl> idents; private final Map<String, CelFunctionDecl> functions; /** Construct an empty {@code DeclGroup}. */ public DeclGroup() { this(new HashMap<>(), new HashMap<>()); } /** Construct a new {@code DeclGroup} from the input {@code idents} and {@code functions}. */ public DeclGroup(Map<String, CelIdentDecl> idents, Map<String, CelFunctionDecl> functions) { this.functions = functions; this.idents = idents; } /** * Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name. */ public Map<String, CelIdentDecl> getIdents() { return ImmutableMap.copyOf(idents); } /** Get an immutable map of the functions in the {@code DeclGroup} keyed by declaration name. */ public Map<String, CelFunctionDecl> getFunctions() { return ImmutableMap.copyOf(functions); } /** Get an identifier declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelIdentDecl getIdent(String name) { return idents.get(name); } /** Put an identifier declaration into the {@code DeclGroup}. */ public void putIdent(CelIdentDecl ident) { idents.put(ident.name(), ident); } /** Get a function declaration by {@code name}. Returns {@code null} if absent. */ public @Nullable CelFunctionDecl getFunction(String name) { return functions.get(name); } /** Put a function declaration into the {@code DeclGroup}. */ public void putFunction(CelFunctionDecl function) { functions.put(function.name(), function); } /** Create a copy of the {@code DeclGroup} with immutable identifier and function maps. */ public DeclGroup immutableCopy() { return new DeclGroup(getIdents(), getFunctions()); } } /** * Sanitize the identifier declaration type making sure that proto-based message names are mapped * to the appropriate CEL type. */ private static CelIdentDecl sanitizeIdent(CelIdentDecl decl) { CelType type = decl.type(); if (!isWellKnownType(type)) { return decl; } return CelIdentDecl.newIdentDeclaration(decl.name(), getWellKnownType(decl.type())); } /** * Sanitize the function declaration type making sure that proto-based message names appearing in * the result or parameter types are mapped to the appropriate CEL types. */ private static CelFunctionDecl sanitizeFunction(CelFunctionDecl func) { boolean needsSanitizing = false; for (CelOverloadDecl o : func.overloads()) { if (isWellKnownType(o.resultType())) { needsSanitizing = true; break; } for (CelType p : o.parameterTypes()) { if (isWellKnownType(p)) { needsSanitizing = true; break; } } } if (!needsSanitizing) { return func; } CelFunctionDecl.Builder funcBuilder = func.toBuilder(); ImmutableSet.Builder<CelOverloadDecl> overloadsBuilder = new ImmutableSet.Builder<>(); for (CelOverloadDecl overloadDecl : funcBuilder.overloads()) { CelOverloadDecl.Builder overloadBuilder = overloadDecl.toBuilder(); CelType resultType = overloadBuilder.build().resultType(); if (isWellKnownType(resultType)) { overloadBuilder.setResultType(getWellKnownType(resultType)); } ImmutableList.Builder<CelType> parameterTypeBuilder = ImmutableList.builder(); for (CelType paramType : overloadBuilder.parameterTypes()) { if (isWellKnownType(paramType)) { parameterTypeBuilder.add(getWellKnownType(paramType)); } else { parameterTypeBuilder.add(paramType); } } overloadBuilder.setParameterTypes(parameterTypeBuilder.build()); overloadsBuilder.add(overloadBuilder.build()); } return funcBuilder.setOverloads(overloadsBuilder.build()).build(); } static boolean isWellKnownType(CelType type) { return type.kind() == CelKind.STRUCT && CelTypes.isWellKnownType(type.name()); } static CelType getWellKnownType(CelType type) { Preconditions.checkArgument(type.kind() == CelKind.STRUCT); return CelTypes.getWellKnownCelType(type.name()).get(); } }
googleapis/google-cloud-java
35,297
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetIamPolicyInstanceRequest.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 Instances.GetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetIamPolicyInstanceRequest} */ public final class GetIamPolicyInstanceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetIamPolicyInstanceRequest) GetIamPolicyInstanceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetIamPolicyInstanceRequest.newBuilder() to construct. private GetIamPolicyInstanceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetIamPolicyInstanceRequest() { project_ = ""; resource_ = ""; zone_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetIamPolicyInstanceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.class, com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.Builder.class); } private int bitField0_; public static final int OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER = 499220029; private int optionsRequestedPolicyVersion_ = 0; /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return Whether the optionsRequestedPolicyVersion field is set. */ @java.lang.Override public boolean hasOptionsRequestedPolicyVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return The optionsRequestedPolicyVersion. */ @java.lang.Override public int getOptionsRequestedPolicyVersion() { return optionsRequestedPolicyVersion_; } public static final int PROJECT_FIELD_NUMBER = 227560217; @SuppressWarnings("serial") private volatile java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int 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; } } public static final int ZONE_FIELD_NUMBER = 3744684; @SuppressWarnings("serial") private volatile java.lang.Object zone_ = ""; /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The zone. */ @java.lang.Override public java.lang.String getZone() { java.lang.Object ref = zone_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zone_ = s; return s; } } /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for zone. */ @java.lang.Override public com.google.protobuf.ByteString getZoneBytes() { java.lang.Object ref = zone_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); zone_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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(zone_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3744684, zone_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeInt32(499220029, optionsRequestedPolicyVersion_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(zone_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3744684, zone_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(195806222, resource_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size( 499220029, optionsRequestedPolicyVersion_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.GetIamPolicyInstanceRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GetIamPolicyInstanceRequest other = (com.google.cloud.compute.v1.GetIamPolicyInstanceRequest) obj; if (hasOptionsRequestedPolicyVersion() != other.hasOptionsRequestedPolicyVersion()) return false; if (hasOptionsRequestedPolicyVersion()) { if (getOptionsRequestedPolicyVersion() != other.getOptionsRequestedPolicyVersion()) return false; } if (!getProject().equals(other.getProject())) return false; if (!getResource().equals(other.getResource())) return false; if (!getZone().equals(other.getZone())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasOptionsRequestedPolicyVersion()) { hash = (37 * hash) + OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER; hash = (53 * hash) + getOptionsRequestedPolicyVersion(); } hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); hash = (37 * hash) + RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getResource().hashCode(); hash = (37 * hash) + ZONE_FIELD_NUMBER; hash = (53 * hash) + getZone().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest 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.GetIamPolicyInstanceRequest 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 Instances.GetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetIamPolicyInstanceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetIamPolicyInstanceRequest) com.google.cloud.compute.v1.GetIamPolicyInstanceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetIamPolicyInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.class, com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; optionsRequestedPolicyVersion_ = 0; project_ = ""; resource_ = ""; zone_ = ""; 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_GetIamPolicyInstanceRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyInstanceRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyInstanceRequest build() { com.google.cloud.compute.v1.GetIamPolicyInstanceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyInstanceRequest buildPartial() { com.google.cloud.compute.v1.GetIamPolicyInstanceRequest result = new com.google.cloud.compute.v1.GetIamPolicyInstanceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.GetIamPolicyInstanceRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.optionsRequestedPolicyVersion_ = optionsRequestedPolicyVersion_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.resource_ = resource_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.zone_ = zone_; } 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.GetIamPolicyInstanceRequest) { return mergeFrom((com.google.cloud.compute.v1.GetIamPolicyInstanceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.GetIamPolicyInstanceRequest other) { if (other == com.google.cloud.compute.v1.GetIamPolicyInstanceRequest.getDefaultInstance()) return this; if (other.hasOptionsRequestedPolicyVersion()) { setOptionsRequestedPolicyVersion(other.getOptionsRequestedPolicyVersion()); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getResource().isEmpty()) { resource_ = other.resource_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getZone().isEmpty()) { zone_ = other.zone_; 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 29957474: { zone_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 29957474 case 1566449778: { resource_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 1566449778 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1820481738 case -301207064: { optionsRequestedPolicyVersion_ = input.readInt32(); bitField0_ |= 0x00000001; break; } // case -301207064 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int optionsRequestedPolicyVersion_; /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return Whether the optionsRequestedPolicyVersion field is set. */ @java.lang.Override public boolean hasOptionsRequestedPolicyVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return The optionsRequestedPolicyVersion. */ @java.lang.Override public int getOptionsRequestedPolicyVersion() { return optionsRequestedPolicyVersion_; } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @param value The optionsRequestedPolicyVersion to set. * @return This builder for chaining. */ public Builder setOptionsRequestedPolicyVersion(int value) { optionsRequestedPolicyVersion_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Requested IAM Policy version. * </pre> * * <code>optional int32 options_requested_policy_version = 499220029;</code> * * @return This builder for chaining. */ public Builder clearOptionsRequestedPolicyVersion() { bitField0_ = (bitField0_ & ~0x00000001); optionsRequestedPolicyVersion_ = 0; onChanged(); return this; } private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object 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; } private java.lang.Object zone_ = ""; /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The zone. */ public java.lang.String getZone() { java.lang.Object ref = zone_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); zone_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for zone. */ public com.google.protobuf.ByteString getZoneBytes() { java.lang.Object ref = zone_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); zone_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The zone to set. * @return This builder for chaining. */ public Builder setZone(java.lang.String value) { if (value == null) { throw new NullPointerException(); } zone_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearZone() { zone_ = getDefaultInstance().getZone(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * The name of the zone for this request. * </pre> * * <code>string zone = 3744684 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for zone to set. * @return This builder for chaining. */ public Builder setZoneBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); zone_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.GetIamPolicyInstanceRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetIamPolicyInstanceRequest) private static final com.google.cloud.compute.v1.GetIamPolicyInstanceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetIamPolicyInstanceRequest(); } public static com.google.cloud.compute.v1.GetIamPolicyInstanceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetIamPolicyInstanceRequest> PARSER = new com.google.protobuf.AbstractParser<GetIamPolicyInstanceRequest>() { @java.lang.Override public GetIamPolicyInstanceRequest 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<GetIamPolicyInstanceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetIamPolicyInstanceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GetIamPolicyInstanceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,386
java-monitoring-metricsscope/proto-google-cloud-monitoring-metricsscope-v1/src/main/java/com/google/monitoring/metricsscope/v1/ListMetricsScopesByMonitoredProjectResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/metricsscope/v1/metrics_scopes.proto // Protobuf Java Version: 3.25.8 package com.google.monitoring.metricsscope.v1; /** * * * <pre> * Response for the `ListMetricsScopesByMonitoredProject` method. * </pre> * * Protobuf type {@code * google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse} */ public final class ListMetricsScopesByMonitoredProjectResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) ListMetricsScopesByMonitoredProjectResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListMetricsScopesByMonitoredProjectResponse.newBuilder() to construct. private ListMetricsScopesByMonitoredProjectResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListMetricsScopesByMonitoredProjectResponse() { metricsScopes_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListMetricsScopesByMonitoredProjectResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.metricsscope.v1.MetricsScopesProto .internal_static_google_monitoring_metricsscope_v1_ListMetricsScopesByMonitoredProjectResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.metricsscope.v1.MetricsScopesProto .internal_static_google_monitoring_metricsscope_v1_ListMetricsScopesByMonitoredProjectResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse.class, com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse .Builder.class); } public static final int METRICS_SCOPES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.monitoring.metricsscope.v1.MetricsScope> metricsScopes_; /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ @java.lang.Override public java.util.List<com.google.monitoring.metricsscope.v1.MetricsScope> getMetricsScopesList() { return metricsScopes_; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder> getMetricsScopesOrBuilderList() { return metricsScopes_; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ @java.lang.Override public int getMetricsScopesCount() { return metricsScopes_.size(); } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ @java.lang.Override public com.google.monitoring.metricsscope.v1.MetricsScope getMetricsScopes(int index) { return metricsScopes_.get(index); } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ @java.lang.Override public com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder getMetricsScopesOrBuilder( int index) { return metricsScopes_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < metricsScopes_.size(); i++) { output.writeMessage(1, metricsScopes_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < metricsScopes_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, metricsScopes_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse)) { return super.equals(obj); } com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse other = (com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) obj; if (!getMetricsScopesList().equals(other.getMetricsScopesList())) 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 (getMetricsScopesCount() > 0) { hash = (37 * hash) + METRICS_SCOPES_FIELD_NUMBER; hash = (53 * hash) + getMetricsScopesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse 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 `ListMetricsScopesByMonitoredProject` method. * </pre> * * Protobuf type {@code * google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.metricsscope.v1.MetricsScopesProto .internal_static_google_monitoring_metricsscope_v1_ListMetricsScopesByMonitoredProjectResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.metricsscope.v1.MetricsScopesProto .internal_static_google_monitoring_metricsscope_v1_ListMetricsScopesByMonitoredProjectResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse .class, com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse .Builder.class); } // Construct using // com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (metricsScopesBuilder_ == null) { metricsScopes_ = java.util.Collections.emptyList(); } else { metricsScopes_ = null; metricsScopesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.monitoring.metricsscope.v1.MetricsScopesProto .internal_static_google_monitoring_metricsscope_v1_ListMetricsScopesByMonitoredProjectResponse_descriptor; } @java.lang.Override public com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse getDefaultInstanceForType() { return com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse .getDefaultInstance(); } @java.lang.Override public com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse build() { com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse buildPartial() { com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse result = new com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse( this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse result) { if (metricsScopesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { metricsScopes_ = java.util.Collections.unmodifiableList(metricsScopes_); bitField0_ = (bitField0_ & ~0x00000001); } result.metricsScopes_ = metricsScopes_; } else { result.metricsScopes_ = metricsScopesBuilder_.build(); } } private void buildPartial0( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) { return mergeFrom( (com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse other) { if (other == com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse .getDefaultInstance()) return this; if (metricsScopesBuilder_ == null) { if (!other.metricsScopes_.isEmpty()) { if (metricsScopes_.isEmpty()) { metricsScopes_ = other.metricsScopes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureMetricsScopesIsMutable(); metricsScopes_.addAll(other.metricsScopes_); } onChanged(); } } else { if (!other.metricsScopes_.isEmpty()) { if (metricsScopesBuilder_.isEmpty()) { metricsScopesBuilder_.dispose(); metricsScopesBuilder_ = null; metricsScopes_ = other.metricsScopes_; bitField0_ = (bitField0_ & ~0x00000001); metricsScopesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getMetricsScopesFieldBuilder() : null; } else { metricsScopesBuilder_.addAllMessages(other.metricsScopes_); } } } 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.monitoring.metricsscope.v1.MetricsScope m = input.readMessage( com.google.monitoring.metricsscope.v1.MetricsScope.parser(), extensionRegistry); if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); metricsScopes_.add(m); } else { metricsScopesBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.monitoring.metricsscope.v1.MetricsScope> metricsScopes_ = java.util.Collections.emptyList(); private void ensureMetricsScopesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { metricsScopes_ = new java.util.ArrayList<com.google.monitoring.metricsscope.v1.MetricsScope>( metricsScopes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.metricsscope.v1.MetricsScope, com.google.monitoring.metricsscope.v1.MetricsScope.Builder, com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder> metricsScopesBuilder_; /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public java.util.List<com.google.monitoring.metricsscope.v1.MetricsScope> getMetricsScopesList() { if (metricsScopesBuilder_ == null) { return java.util.Collections.unmodifiableList(metricsScopes_); } else { return metricsScopesBuilder_.getMessageList(); } } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public int getMetricsScopesCount() { if (metricsScopesBuilder_ == null) { return metricsScopes_.size(); } else { return metricsScopesBuilder_.getCount(); } } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public com.google.monitoring.metricsscope.v1.MetricsScope getMetricsScopes(int index) { if (metricsScopesBuilder_ == null) { return metricsScopes_.get(index); } else { return metricsScopesBuilder_.getMessage(index); } } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder setMetricsScopes( int index, com.google.monitoring.metricsscope.v1.MetricsScope value) { if (metricsScopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricsScopesIsMutable(); metricsScopes_.set(index, value); onChanged(); } else { metricsScopesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder setMetricsScopes( int index, com.google.monitoring.metricsscope.v1.MetricsScope.Builder builderForValue) { if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); metricsScopes_.set(index, builderForValue.build()); onChanged(); } else { metricsScopesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder addMetricsScopes(com.google.monitoring.metricsscope.v1.MetricsScope value) { if (metricsScopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricsScopesIsMutable(); metricsScopes_.add(value); onChanged(); } else { metricsScopesBuilder_.addMessage(value); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder addMetricsScopes( int index, com.google.monitoring.metricsscope.v1.MetricsScope value) { if (metricsScopesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricsScopesIsMutable(); metricsScopes_.add(index, value); onChanged(); } else { metricsScopesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder addMetricsScopes( com.google.monitoring.metricsscope.v1.MetricsScope.Builder builderForValue) { if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); metricsScopes_.add(builderForValue.build()); onChanged(); } else { metricsScopesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder addMetricsScopes( int index, com.google.monitoring.metricsscope.v1.MetricsScope.Builder builderForValue) { if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); metricsScopes_.add(index, builderForValue.build()); onChanged(); } else { metricsScopesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder addAllMetricsScopes( java.lang.Iterable<? extends com.google.monitoring.metricsscope.v1.MetricsScope> values) { if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, metricsScopes_); onChanged(); } else { metricsScopesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder clearMetricsScopes() { if (metricsScopesBuilder_ == null) { metricsScopes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { metricsScopesBuilder_.clear(); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public Builder removeMetricsScopes(int index) { if (metricsScopesBuilder_ == null) { ensureMetricsScopesIsMutable(); metricsScopes_.remove(index); onChanged(); } else { metricsScopesBuilder_.remove(index); } return this; } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public com.google.monitoring.metricsscope.v1.MetricsScope.Builder getMetricsScopesBuilder( int index) { return getMetricsScopesFieldBuilder().getBuilder(index); } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder getMetricsScopesOrBuilder( int index) { if (metricsScopesBuilder_ == null) { return metricsScopes_.get(index); } else { return metricsScopesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public java.util.List<? extends com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder> getMetricsScopesOrBuilderList() { if (metricsScopesBuilder_ != null) { return metricsScopesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(metricsScopes_); } } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public com.google.monitoring.metricsscope.v1.MetricsScope.Builder addMetricsScopesBuilder() { return getMetricsScopesFieldBuilder() .addBuilder(com.google.monitoring.metricsscope.v1.MetricsScope.getDefaultInstance()); } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public com.google.monitoring.metricsscope.v1.MetricsScope.Builder addMetricsScopesBuilder( int index) { return getMetricsScopesFieldBuilder() .addBuilder( index, com.google.monitoring.metricsscope.v1.MetricsScope.getDefaultInstance()); } /** * * * <pre> * A set of all metrics scopes that the specified monitored project has been * added to. * </pre> * * <code>repeated .google.monitoring.metricsscope.v1.MetricsScope metrics_scopes = 1;</code> */ public java.util.List<com.google.monitoring.metricsscope.v1.MetricsScope.Builder> getMetricsScopesBuilderList() { return getMetricsScopesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.metricsscope.v1.MetricsScope, com.google.monitoring.metricsscope.v1.MetricsScope.Builder, com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder> getMetricsScopesFieldBuilder() { if (metricsScopesBuilder_ == null) { metricsScopesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.metricsscope.v1.MetricsScope, com.google.monitoring.metricsscope.v1.MetricsScope.Builder, com.google.monitoring.metricsscope.v1.MetricsScopeOrBuilder>( metricsScopes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); metricsScopes_ = null; } return metricsScopesBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) } // @@protoc_insertion_point(class_scope:google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse) private static final com.google.monitoring.metricsscope.v1 .ListMetricsScopesByMonitoredProjectResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse(); } public static com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListMetricsScopesByMonitoredProjectResponse> PARSER = new com.google.protobuf.AbstractParser<ListMetricsScopesByMonitoredProjectResponse>() { @java.lang.Override public ListMetricsScopesByMonitoredProjectResponse 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<ListMetricsScopesByMonitoredProjectResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListMetricsScopesByMonitoredProjectResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.monitoring.metricsscope.v1.ListMetricsScopesByMonitoredProjectResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,399
java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/UpdateConversationProfileRequest.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/conversation_profile.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2; /** * * * <pre> * The request message for * [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.UpdateConversationProfileRequest} */ public final class UpdateConversationProfileRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.UpdateConversationProfileRequest) UpdateConversationProfileRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateConversationProfileRequest.newBuilder() to construct. private UpdateConversationProfileRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateConversationProfileRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateConversationProfileRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.ConversationProfileProto .internal_static_google_cloud_dialogflow_v2_UpdateConversationProfileRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.ConversationProfileProto .internal_static_google_cloud_dialogflow_v2_UpdateConversationProfileRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.class, com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.Builder.class); } private int bitField0_; public static final int CONVERSATION_PROFILE_FIELD_NUMBER = 1; private com.google.cloud.dialogflow.v2.ConversationProfile conversationProfile_; /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversationProfile field is set. */ @java.lang.Override public boolean hasConversationProfile() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversationProfile. */ @java.lang.Override public com.google.cloud.dialogflow.v2.ConversationProfile getConversationProfile() { return conversationProfile_ == null ? com.google.cloud.dialogflow.v2.ConversationProfile.getDefaultInstance() : conversationProfile_; } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.ConversationProfileOrBuilder getConversationProfileOrBuilder() { return conversationProfile_ == null ? com.google.cloud.dialogflow.v2.ConversationProfile.getDefaultInstance() : conversationProfile_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. The mask to control which fields to update. * </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, getConversationProfile()); } 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, getConversationProfile()); } 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.dialogflow.v2.UpdateConversationProfileRequest)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest other = (com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest) obj; if (hasConversationProfile() != other.hasConversationProfile()) return false; if (hasConversationProfile()) { if (!getConversationProfile().equals(other.getConversationProfile())) 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 (hasConversationProfile()) { hash = (37 * hash) + CONVERSATION_PROFILE_FIELD_NUMBER; hash = (53 * hash) + getConversationProfile().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.dialogflow.v2.UpdateConversationProfileRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest 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.UpdateConversationProfileRequest 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 * [ConversationProfiles.UpdateConversationProfile][google.cloud.dialogflow.v2.ConversationProfiles.UpdateConversationProfile]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.UpdateConversationProfileRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.UpdateConversationProfileRequest) com.google.cloud.dialogflow.v2.UpdateConversationProfileRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.ConversationProfileProto .internal_static_google_cloud_dialogflow_v2_UpdateConversationProfileRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.ConversationProfileProto .internal_static_google_cloud_dialogflow_v2_UpdateConversationProfileRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.class, com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getConversationProfileFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; conversationProfile_ = null; if (conversationProfileBuilder_ != null) { conversationProfileBuilder_.dispose(); conversationProfileBuilder_ = 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.dialogflow.v2.ConversationProfileProto .internal_static_google_cloud_dialogflow_v2_UpdateConversationProfileRequest_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest build() { com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest buildPartial() { com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest result = new com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.conversationProfile_ = conversationProfileBuilder_ == null ? conversationProfile_ : conversationProfileBuilder_.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.dialogflow.v2.UpdateConversationProfileRequest) { return mergeFrom((com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest other) { if (other == com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest.getDefaultInstance()) return this; if (other.hasConversationProfile()) { mergeConversationProfile(other.getConversationProfile()); } 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( getConversationProfileFieldBuilder().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.dialogflow.v2.ConversationProfile conversationProfile_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.ConversationProfile, com.google.cloud.dialogflow.v2.ConversationProfile.Builder, com.google.cloud.dialogflow.v2.ConversationProfileOrBuilder> conversationProfileBuilder_; /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversationProfile field is set. */ public boolean hasConversationProfile() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversationProfile. */ public com.google.cloud.dialogflow.v2.ConversationProfile getConversationProfile() { if (conversationProfileBuilder_ == null) { return conversationProfile_ == null ? com.google.cloud.dialogflow.v2.ConversationProfile.getDefaultInstance() : conversationProfile_; } else { return conversationProfileBuilder_.getMessage(); } } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversationProfile( com.google.cloud.dialogflow.v2.ConversationProfile value) { if (conversationProfileBuilder_ == null) { if (value == null) { throw new NullPointerException(); } conversationProfile_ = value; } else { conversationProfileBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversationProfile( com.google.cloud.dialogflow.v2.ConversationProfile.Builder builderForValue) { if (conversationProfileBuilder_ == null) { conversationProfile_ = builderForValue.build(); } else { conversationProfileBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeConversationProfile( com.google.cloud.dialogflow.v2.ConversationProfile value) { if (conversationProfileBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && conversationProfile_ != null && conversationProfile_ != com.google.cloud.dialogflow.v2.ConversationProfile.getDefaultInstance()) { getConversationProfileBuilder().mergeFrom(value); } else { conversationProfile_ = value; } } else { conversationProfileBuilder_.mergeFrom(value); } if (conversationProfile_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearConversationProfile() { bitField0_ = (bitField0_ & ~0x00000001); conversationProfile_ = null; if (conversationProfileBuilder_ != null) { conversationProfileBuilder_.dispose(); conversationProfileBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.v2.ConversationProfile.Builder getConversationProfileBuilder() { bitField0_ |= 0x00000001; onChanged(); return getConversationProfileFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.v2.ConversationProfileOrBuilder getConversationProfileOrBuilder() { if (conversationProfileBuilder_ != null) { return conversationProfileBuilder_.getMessageOrBuilder(); } else { return conversationProfile_ == null ? com.google.cloud.dialogflow.v2.ConversationProfile.getDefaultInstance() : conversationProfile_; } } /** * * * <pre> * Required. The conversation profile to update. * </pre> * * <code> * .google.cloud.dialogflow.v2.ConversationProfile conversation_profile = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.ConversationProfile, com.google.cloud.dialogflow.v2.ConversationProfile.Builder, com.google.cloud.dialogflow.v2.ConversationProfileOrBuilder> getConversationProfileFieldBuilder() { if (conversationProfileBuilder_ == null) { conversationProfileBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2.ConversationProfile, com.google.cloud.dialogflow.v2.ConversationProfile.Builder, com.google.cloud.dialogflow.v2.ConversationProfileOrBuilder>( getConversationProfile(), getParentForChildren(), isClean()); conversationProfile_ = null; } return conversationProfileBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The mask to control which fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. The mask to control which fields to update. * </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.dialogflow.v2.UpdateConversationProfileRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.UpdateConversationProfileRequest) private static final com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest(); } public static com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateConversationProfileRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateConversationProfileRequest>() { @java.lang.Override public UpdateConversationProfileRequest 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<UpdateConversationProfileRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateConversationProfileRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.UpdateConversationProfileRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hive
35,391
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/RolePrincipalGrant.java
/** * Autogenerated by Thrift Compiler (0.16.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.16.0)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class RolePrincipalGrant implements org.apache.thrift.TBase<RolePrincipalGrant, RolePrincipalGrant._Fields>, java.io.Serializable, Cloneable, Comparable<RolePrincipalGrant> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("RolePrincipalGrant"); private static final org.apache.thrift.protocol.TField ROLE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("roleName", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField PRINCIPAL_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("principalName", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField PRINCIPAL_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("principalType", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField GRANT_OPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("grantOption", org.apache.thrift.protocol.TType.BOOL, (short)4); private static final org.apache.thrift.protocol.TField GRANT_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("grantTime", org.apache.thrift.protocol.TType.I32, (short)5); private static final org.apache.thrift.protocol.TField GRANTOR_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("grantorName", org.apache.thrift.protocol.TType.STRING, (short)6); private static final org.apache.thrift.protocol.TField GRANTOR_PRINCIPAL_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("grantorPrincipalType", org.apache.thrift.protocol.TType.I32, (short)7); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new RolePrincipalGrantStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new RolePrincipalGrantTupleSchemeFactory(); private @org.apache.thrift.annotation.Nullable java.lang.String roleName; // required private @org.apache.thrift.annotation.Nullable java.lang.String principalName; // required private @org.apache.thrift.annotation.Nullable PrincipalType principalType; // required private boolean grantOption; // required private int grantTime; // required private @org.apache.thrift.annotation.Nullable java.lang.String grantorName; // required private @org.apache.thrift.annotation.Nullable PrincipalType grantorPrincipalType; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { ROLE_NAME((short)1, "roleName"), PRINCIPAL_NAME((short)2, "principalName"), /** * * @see PrincipalType */ PRINCIPAL_TYPE((short)3, "principalType"), GRANT_OPTION((short)4, "grantOption"), GRANT_TIME((short)5, "grantTime"), GRANTOR_NAME((short)6, "grantorName"), /** * * @see PrincipalType */ GRANTOR_PRINCIPAL_TYPE((short)7, "grantorPrincipalType"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // ROLE_NAME return ROLE_NAME; case 2: // PRINCIPAL_NAME return PRINCIPAL_NAME; case 3: // PRINCIPAL_TYPE return PRINCIPAL_TYPE; case 4: // GRANT_OPTION return GRANT_OPTION; case 5: // GRANT_TIME return GRANT_TIME; case 6: // GRANTOR_NAME return GRANTOR_NAME; case 7: // GRANTOR_PRINCIPAL_TYPE return GRANTOR_PRINCIPAL_TYPE; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final int __GRANTOPTION_ISSET_ID = 0; private static final int __GRANTTIME_ISSET_ID = 1; private byte __isset_bitfield = 0; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.ROLE_NAME, new org.apache.thrift.meta_data.FieldMetaData("roleName", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PRINCIPAL_NAME, new org.apache.thrift.meta_data.FieldMetaData("principalName", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PRINCIPAL_TYPE, new org.apache.thrift.meta_data.FieldMetaData("principalType", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PrincipalType.class))); tmpMap.put(_Fields.GRANT_OPTION, new org.apache.thrift.meta_data.FieldMetaData("grantOption", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.GRANT_TIME, new org.apache.thrift.meta_data.FieldMetaData("grantTime", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.GRANTOR_NAME, new org.apache.thrift.meta_data.FieldMetaData("grantorName", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.GRANTOR_PRINCIPAL_TYPE, new org.apache.thrift.meta_data.FieldMetaData("grantorPrincipalType", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PrincipalType.class))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RolePrincipalGrant.class, metaDataMap); } public RolePrincipalGrant() { } public RolePrincipalGrant( java.lang.String roleName, java.lang.String principalName, PrincipalType principalType, boolean grantOption, int grantTime, java.lang.String grantorName, PrincipalType grantorPrincipalType) { this(); this.roleName = roleName; this.principalName = principalName; this.principalType = principalType; this.grantOption = grantOption; setGrantOptionIsSet(true); this.grantTime = grantTime; setGrantTimeIsSet(true); this.grantorName = grantorName; this.grantorPrincipalType = grantorPrincipalType; } /** * Performs a deep copy on <i>other</i>. */ public RolePrincipalGrant(RolePrincipalGrant other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetRoleName()) { this.roleName = other.roleName; } if (other.isSetPrincipalName()) { this.principalName = other.principalName; } if (other.isSetPrincipalType()) { this.principalType = other.principalType; } this.grantOption = other.grantOption; this.grantTime = other.grantTime; if (other.isSetGrantorName()) { this.grantorName = other.grantorName; } if (other.isSetGrantorPrincipalType()) { this.grantorPrincipalType = other.grantorPrincipalType; } } public RolePrincipalGrant deepCopy() { return new RolePrincipalGrant(this); } @Override public void clear() { this.roleName = null; this.principalName = null; this.principalType = null; setGrantOptionIsSet(false); this.grantOption = false; setGrantTimeIsSet(false); this.grantTime = 0; this.grantorName = null; this.grantorPrincipalType = null; } @org.apache.thrift.annotation.Nullable public java.lang.String getRoleName() { return this.roleName; } public void setRoleName(@org.apache.thrift.annotation.Nullable java.lang.String roleName) { this.roleName = roleName; } public void unsetRoleName() { this.roleName = null; } /** Returns true if field roleName is set (has been assigned a value) and false otherwise */ public boolean isSetRoleName() { return this.roleName != null; } public void setRoleNameIsSet(boolean value) { if (!value) { this.roleName = null; } } @org.apache.thrift.annotation.Nullable public java.lang.String getPrincipalName() { return this.principalName; } public void setPrincipalName(@org.apache.thrift.annotation.Nullable java.lang.String principalName) { this.principalName = principalName; } public void unsetPrincipalName() { this.principalName = null; } /** Returns true if field principalName is set (has been assigned a value) and false otherwise */ public boolean isSetPrincipalName() { return this.principalName != null; } public void setPrincipalNameIsSet(boolean value) { if (!value) { this.principalName = null; } } /** * * @see PrincipalType */ @org.apache.thrift.annotation.Nullable public PrincipalType getPrincipalType() { return this.principalType; } /** * * @see PrincipalType */ public void setPrincipalType(@org.apache.thrift.annotation.Nullable PrincipalType principalType) { this.principalType = principalType; } public void unsetPrincipalType() { this.principalType = null; } /** Returns true if field principalType is set (has been assigned a value) and false otherwise */ public boolean isSetPrincipalType() { return this.principalType != null; } public void setPrincipalTypeIsSet(boolean value) { if (!value) { this.principalType = null; } } public boolean isGrantOption() { return this.grantOption; } public void setGrantOption(boolean grantOption) { this.grantOption = grantOption; setGrantOptionIsSet(true); } public void unsetGrantOption() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __GRANTOPTION_ISSET_ID); } /** Returns true if field grantOption is set (has been assigned a value) and false otherwise */ public boolean isSetGrantOption() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __GRANTOPTION_ISSET_ID); } public void setGrantOptionIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __GRANTOPTION_ISSET_ID, value); } public int getGrantTime() { return this.grantTime; } public void setGrantTime(int grantTime) { this.grantTime = grantTime; setGrantTimeIsSet(true); } public void unsetGrantTime() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __GRANTTIME_ISSET_ID); } /** Returns true if field grantTime is set (has been assigned a value) and false otherwise */ public boolean isSetGrantTime() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __GRANTTIME_ISSET_ID); } public void setGrantTimeIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __GRANTTIME_ISSET_ID, value); } @org.apache.thrift.annotation.Nullable public java.lang.String getGrantorName() { return this.grantorName; } public void setGrantorName(@org.apache.thrift.annotation.Nullable java.lang.String grantorName) { this.grantorName = grantorName; } public void unsetGrantorName() { this.grantorName = null; } /** Returns true if field grantorName is set (has been assigned a value) and false otherwise */ public boolean isSetGrantorName() { return this.grantorName != null; } public void setGrantorNameIsSet(boolean value) { if (!value) { this.grantorName = null; } } /** * * @see PrincipalType */ @org.apache.thrift.annotation.Nullable public PrincipalType getGrantorPrincipalType() { return this.grantorPrincipalType; } /** * * @see PrincipalType */ public void setGrantorPrincipalType(@org.apache.thrift.annotation.Nullable PrincipalType grantorPrincipalType) { this.grantorPrincipalType = grantorPrincipalType; } public void unsetGrantorPrincipalType() { this.grantorPrincipalType = null; } /** Returns true if field grantorPrincipalType is set (has been assigned a value) and false otherwise */ public boolean isSetGrantorPrincipalType() { return this.grantorPrincipalType != null; } public void setGrantorPrincipalTypeIsSet(boolean value) { if (!value) { this.grantorPrincipalType = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case ROLE_NAME: if (value == null) { unsetRoleName(); } else { setRoleName((java.lang.String)value); } break; case PRINCIPAL_NAME: if (value == null) { unsetPrincipalName(); } else { setPrincipalName((java.lang.String)value); } break; case PRINCIPAL_TYPE: if (value == null) { unsetPrincipalType(); } else { setPrincipalType((PrincipalType)value); } break; case GRANT_OPTION: if (value == null) { unsetGrantOption(); } else { setGrantOption((java.lang.Boolean)value); } break; case GRANT_TIME: if (value == null) { unsetGrantTime(); } else { setGrantTime((java.lang.Integer)value); } break; case GRANTOR_NAME: if (value == null) { unsetGrantorName(); } else { setGrantorName((java.lang.String)value); } break; case GRANTOR_PRINCIPAL_TYPE: if (value == null) { unsetGrantorPrincipalType(); } else { setGrantorPrincipalType((PrincipalType)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case ROLE_NAME: return getRoleName(); case PRINCIPAL_NAME: return getPrincipalName(); case PRINCIPAL_TYPE: return getPrincipalType(); case GRANT_OPTION: return isGrantOption(); case GRANT_TIME: return getGrantTime(); case GRANTOR_NAME: return getGrantorName(); case GRANTOR_PRINCIPAL_TYPE: return getGrantorPrincipalType(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case ROLE_NAME: return isSetRoleName(); case PRINCIPAL_NAME: return isSetPrincipalName(); case PRINCIPAL_TYPE: return isSetPrincipalType(); case GRANT_OPTION: return isSetGrantOption(); case GRANT_TIME: return isSetGrantTime(); case GRANTOR_NAME: return isSetGrantorName(); case GRANTOR_PRINCIPAL_TYPE: return isSetGrantorPrincipalType(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof RolePrincipalGrant) return this.equals((RolePrincipalGrant)that); return false; } public boolean equals(RolePrincipalGrant that) { if (that == null) return false; if (this == that) return true; boolean this_present_roleName = true && this.isSetRoleName(); boolean that_present_roleName = true && that.isSetRoleName(); if (this_present_roleName || that_present_roleName) { if (!(this_present_roleName && that_present_roleName)) return false; if (!this.roleName.equals(that.roleName)) return false; } boolean this_present_principalName = true && this.isSetPrincipalName(); boolean that_present_principalName = true && that.isSetPrincipalName(); if (this_present_principalName || that_present_principalName) { if (!(this_present_principalName && that_present_principalName)) return false; if (!this.principalName.equals(that.principalName)) return false; } boolean this_present_principalType = true && this.isSetPrincipalType(); boolean that_present_principalType = true && that.isSetPrincipalType(); if (this_present_principalType || that_present_principalType) { if (!(this_present_principalType && that_present_principalType)) return false; if (!this.principalType.equals(that.principalType)) return false; } boolean this_present_grantOption = true; boolean that_present_grantOption = true; if (this_present_grantOption || that_present_grantOption) { if (!(this_present_grantOption && that_present_grantOption)) return false; if (this.grantOption != that.grantOption) return false; } boolean this_present_grantTime = true; boolean that_present_grantTime = true; if (this_present_grantTime || that_present_grantTime) { if (!(this_present_grantTime && that_present_grantTime)) return false; if (this.grantTime != that.grantTime) return false; } boolean this_present_grantorName = true && this.isSetGrantorName(); boolean that_present_grantorName = true && that.isSetGrantorName(); if (this_present_grantorName || that_present_grantorName) { if (!(this_present_grantorName && that_present_grantorName)) return false; if (!this.grantorName.equals(that.grantorName)) return false; } boolean this_present_grantorPrincipalType = true && this.isSetGrantorPrincipalType(); boolean that_present_grantorPrincipalType = true && that.isSetGrantorPrincipalType(); if (this_present_grantorPrincipalType || that_present_grantorPrincipalType) { if (!(this_present_grantorPrincipalType && that_present_grantorPrincipalType)) return false; if (!this.grantorPrincipalType.equals(that.grantorPrincipalType)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetRoleName()) ? 131071 : 524287); if (isSetRoleName()) hashCode = hashCode * 8191 + roleName.hashCode(); hashCode = hashCode * 8191 + ((isSetPrincipalName()) ? 131071 : 524287); if (isSetPrincipalName()) hashCode = hashCode * 8191 + principalName.hashCode(); hashCode = hashCode * 8191 + ((isSetPrincipalType()) ? 131071 : 524287); if (isSetPrincipalType()) hashCode = hashCode * 8191 + principalType.getValue(); hashCode = hashCode * 8191 + ((grantOption) ? 131071 : 524287); hashCode = hashCode * 8191 + grantTime; hashCode = hashCode * 8191 + ((isSetGrantorName()) ? 131071 : 524287); if (isSetGrantorName()) hashCode = hashCode * 8191 + grantorName.hashCode(); hashCode = hashCode * 8191 + ((isSetGrantorPrincipalType()) ? 131071 : 524287); if (isSetGrantorPrincipalType()) hashCode = hashCode * 8191 + grantorPrincipalType.getValue(); return hashCode; } @Override public int compareTo(RolePrincipalGrant other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetRoleName(), other.isSetRoleName()); if (lastComparison != 0) { return lastComparison; } if (isSetRoleName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.roleName, other.roleName); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetPrincipalName(), other.isSetPrincipalName()); if (lastComparison != 0) { return lastComparison; } if (isSetPrincipalName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.principalName, other.principalName); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetPrincipalType(), other.isSetPrincipalType()); if (lastComparison != 0) { return lastComparison; } if (isSetPrincipalType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.principalType, other.principalType); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetGrantOption(), other.isSetGrantOption()); if (lastComparison != 0) { return lastComparison; } if (isSetGrantOption()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantOption, other.grantOption); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetGrantTime(), other.isSetGrantTime()); if (lastComparison != 0) { return lastComparison; } if (isSetGrantTime()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantTime, other.grantTime); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetGrantorName(), other.isSetGrantorName()); if (lastComparison != 0) { return lastComparison; } if (isSetGrantorName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantorName, other.grantorName); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetGrantorPrincipalType(), other.isSetGrantorPrincipalType()); if (lastComparison != 0) { return lastComparison; } if (isSetGrantorPrincipalType()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantorPrincipalType, other.grantorPrincipalType); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("RolePrincipalGrant("); boolean first = true; sb.append("roleName:"); if (this.roleName == null) { sb.append("null"); } else { sb.append(this.roleName); } first = false; if (!first) sb.append(", "); sb.append("principalName:"); if (this.principalName == null) { sb.append("null"); } else { sb.append(this.principalName); } first = false; if (!first) sb.append(", "); sb.append("principalType:"); if (this.principalType == null) { sb.append("null"); } else { sb.append(this.principalType); } first = false; if (!first) sb.append(", "); sb.append("grantOption:"); sb.append(this.grantOption); first = false; if (!first) sb.append(", "); sb.append("grantTime:"); sb.append(this.grantTime); first = false; if (!first) sb.append(", "); sb.append("grantorName:"); if (this.grantorName == null) { sb.append("null"); } else { sb.append(this.grantorName); } first = false; if (!first) sb.append(", "); sb.append("grantorPrincipalType:"); if (this.grantorPrincipalType == null) { sb.append("null"); } else { sb.append(this.grantorPrincipalType); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class RolePrincipalGrantStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public RolePrincipalGrantStandardScheme getScheme() { return new RolePrincipalGrantStandardScheme(); } } private static class RolePrincipalGrantStandardScheme extends org.apache.thrift.scheme.StandardScheme<RolePrincipalGrant> { public void read(org.apache.thrift.protocol.TProtocol iprot, RolePrincipalGrant struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // ROLE_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.roleName = iprot.readString(); struct.setRoleNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PRINCIPAL_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.principalName = iprot.readString(); struct.setPrincipalNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PRINCIPAL_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.principalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32()); struct.setPrincipalTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // GRANT_OPTION if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.grantOption = iprot.readBool(); struct.setGrantOptionIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // GRANT_TIME if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.grantTime = iprot.readI32(); struct.setGrantTimeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // GRANTOR_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.grantorName = iprot.readString(); struct.setGrantorNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // GRANTOR_PRINCIPAL_TYPE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.grantorPrincipalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32()); struct.setGrantorPrincipalTypeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, RolePrincipalGrant struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.roleName != null) { oprot.writeFieldBegin(ROLE_NAME_FIELD_DESC); oprot.writeString(struct.roleName); oprot.writeFieldEnd(); } if (struct.principalName != null) { oprot.writeFieldBegin(PRINCIPAL_NAME_FIELD_DESC); oprot.writeString(struct.principalName); oprot.writeFieldEnd(); } if (struct.principalType != null) { oprot.writeFieldBegin(PRINCIPAL_TYPE_FIELD_DESC); oprot.writeI32(struct.principalType.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldBegin(GRANT_OPTION_FIELD_DESC); oprot.writeBool(struct.grantOption); oprot.writeFieldEnd(); oprot.writeFieldBegin(GRANT_TIME_FIELD_DESC); oprot.writeI32(struct.grantTime); oprot.writeFieldEnd(); if (struct.grantorName != null) { oprot.writeFieldBegin(GRANTOR_NAME_FIELD_DESC); oprot.writeString(struct.grantorName); oprot.writeFieldEnd(); } if (struct.grantorPrincipalType != null) { oprot.writeFieldBegin(GRANTOR_PRINCIPAL_TYPE_FIELD_DESC); oprot.writeI32(struct.grantorPrincipalType.getValue()); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class RolePrincipalGrantTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public RolePrincipalGrantTupleScheme getScheme() { return new RolePrincipalGrantTupleScheme(); } } private static class RolePrincipalGrantTupleScheme extends org.apache.thrift.scheme.TupleScheme<RolePrincipalGrant> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, RolePrincipalGrant struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetRoleName()) { optionals.set(0); } if (struct.isSetPrincipalName()) { optionals.set(1); } if (struct.isSetPrincipalType()) { optionals.set(2); } if (struct.isSetGrantOption()) { optionals.set(3); } if (struct.isSetGrantTime()) { optionals.set(4); } if (struct.isSetGrantorName()) { optionals.set(5); } if (struct.isSetGrantorPrincipalType()) { optionals.set(6); } oprot.writeBitSet(optionals, 7); if (struct.isSetRoleName()) { oprot.writeString(struct.roleName); } if (struct.isSetPrincipalName()) { oprot.writeString(struct.principalName); } if (struct.isSetPrincipalType()) { oprot.writeI32(struct.principalType.getValue()); } if (struct.isSetGrantOption()) { oprot.writeBool(struct.grantOption); } if (struct.isSetGrantTime()) { oprot.writeI32(struct.grantTime); } if (struct.isSetGrantorName()) { oprot.writeString(struct.grantorName); } if (struct.isSetGrantorPrincipalType()) { oprot.writeI32(struct.grantorPrincipalType.getValue()); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, RolePrincipalGrant struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(7); if (incoming.get(0)) { struct.roleName = iprot.readString(); struct.setRoleNameIsSet(true); } if (incoming.get(1)) { struct.principalName = iprot.readString(); struct.setPrincipalNameIsSet(true); } if (incoming.get(2)) { struct.principalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32()); struct.setPrincipalTypeIsSet(true); } if (incoming.get(3)) { struct.grantOption = iprot.readBool(); struct.setGrantOptionIsSet(true); } if (incoming.get(4)) { struct.grantTime = iprot.readI32(); struct.setGrantTimeIsSet(true); } if (incoming.get(5)) { struct.grantorName = iprot.readString(); struct.setGrantorNameIsSet(true); } if (incoming.get(6)) { struct.grantorPrincipalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32()); struct.setGrantorPrincipalTypeIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
googleapis/google-cloud-java
35,623
java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1/stub/PredictionServiceStubSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.aiplatform.v1.stub; import static com.google.cloud.aiplatform.v1.PredictionServiceClient.ListLocationsPagedResponse; import com.google.api.HttpBody; 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.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; 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.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.ServerStreamingCallSettings; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StreamingCallSettings; 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.aiplatform.v1.DirectPredictRequest; import com.google.cloud.aiplatform.v1.DirectPredictResponse; import com.google.cloud.aiplatform.v1.DirectRawPredictRequest; import com.google.cloud.aiplatform.v1.DirectRawPredictResponse; import com.google.cloud.aiplatform.v1.ExplainRequest; import com.google.cloud.aiplatform.v1.ExplainResponse; import com.google.cloud.aiplatform.v1.GenerateContentRequest; import com.google.cloud.aiplatform.v1.GenerateContentResponse; import com.google.cloud.aiplatform.v1.PredictRequest; import com.google.cloud.aiplatform.v1.PredictResponse; import com.google.cloud.aiplatform.v1.RawPredictRequest; import com.google.cloud.aiplatform.v1.StreamDirectPredictRequest; import com.google.cloud.aiplatform.v1.StreamDirectPredictResponse; import com.google.cloud.aiplatform.v1.StreamDirectRawPredictRequest; import com.google.cloud.aiplatform.v1.StreamDirectRawPredictResponse; import com.google.cloud.aiplatform.v1.StreamRawPredictRequest; import com.google.cloud.aiplatform.v1.StreamingPredictRequest; import com.google.cloud.aiplatform.v1.StreamingPredictResponse; import com.google.cloud.aiplatform.v1.StreamingRawPredictRequest; import com.google.cloud.aiplatform.v1.StreamingRawPredictResponse; import com.google.cloud.location.GetLocationRequest; import com.google.cloud.location.ListLocationsRequest; import com.google.cloud.location.ListLocationsResponse; import com.google.cloud.location.Location; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; import com.google.iam.v1.SetIamPolicyRequest; import com.google.iam.v1.TestIamPermissionsRequest; import com.google.iam.v1.TestIamPermissionsResponse; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link PredictionServiceStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (aiplatform.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 predict: * * <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 * PredictionServiceStubSettings.Builder predictionServiceSettingsBuilder = * PredictionServiceStubSettings.newBuilder(); * predictionServiceSettingsBuilder * .predictSettings() * .setRetrySettings( * predictionServiceSettingsBuilder * .predictSettings() * .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()); * PredictionServiceStubSettings predictionServiceSettings = * predictionServiceSettingsBuilder.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. */ @Generated("by gapic-generator-java") public class PredictionServiceStubSettings extends StubSettings<PredictionServiceStubSettings> { /** 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") .add("https://www.googleapis.com/auth/cloud-platform.read-only") .build(); private final UnaryCallSettings<PredictRequest, PredictResponse> predictSettings; private final UnaryCallSettings<RawPredictRequest, HttpBody> rawPredictSettings; private final ServerStreamingCallSettings<StreamRawPredictRequest, HttpBody> streamRawPredictSettings; private final UnaryCallSettings<DirectPredictRequest, DirectPredictResponse> directPredictSettings; private final UnaryCallSettings<DirectRawPredictRequest, DirectRawPredictResponse> directRawPredictSettings; private final StreamingCallSettings<StreamDirectPredictRequest, StreamDirectPredictResponse> streamDirectPredictSettings; private final StreamingCallSettings<StreamDirectRawPredictRequest, StreamDirectRawPredictResponse> streamDirectRawPredictSettings; private final StreamingCallSettings<StreamingPredictRequest, StreamingPredictResponse> streamingPredictSettings; private final ServerStreamingCallSettings<StreamingPredictRequest, StreamingPredictResponse> serverStreamingPredictSettings; private final StreamingCallSettings<StreamingRawPredictRequest, StreamingRawPredictResponse> streamingRawPredictSettings; private final UnaryCallSettings<ExplainRequest, ExplainResponse> explainSettings; private final UnaryCallSettings<GenerateContentRequest, GenerateContentResponse> generateContentSettings; private final ServerStreamingCallSettings<GenerateContentRequest, GenerateContentResponse> streamGenerateContentSettings; private final PagedCallSettings< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings; private final UnaryCallSettings<GetLocationRequest, Location> getLocationSettings; private final UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings; private final UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings; private final UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings; private static final PagedListDescriptor<ListLocationsRequest, ListLocationsResponse, Location> LIST_LOCATIONS_PAGE_STR_DESC = new PagedListDescriptor<ListLocationsRequest, ListLocationsResponse, Location>() { @Override public String emptyToken() { return ""; } @Override public ListLocationsRequest injectToken(ListLocationsRequest payload, String token) { return ListLocationsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListLocationsRequest injectPageSize(ListLocationsRequest payload, int pageSize) { return ListLocationsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListLocationsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListLocationsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Location> extractResources(ListLocationsResponse payload) { return payload.getLocationsList(); } }; private static final PagedListResponseFactory< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> LIST_LOCATIONS_PAGE_STR_FACT = new PagedListResponseFactory< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>() { @Override public ApiFuture<ListLocationsPagedResponse> getFuturePagedResponse( UnaryCallable<ListLocationsRequest, ListLocationsResponse> callable, ListLocationsRequest request, ApiCallContext context, ApiFuture<ListLocationsResponse> futureResponse) { PageContext<ListLocationsRequest, ListLocationsResponse, Location> pageContext = PageContext.create(callable, LIST_LOCATIONS_PAGE_STR_DESC, request, context); return ListLocationsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to predict. */ public UnaryCallSettings<PredictRequest, PredictResponse> predictSettings() { return predictSettings; } /** Returns the object with the settings used for calls to rawPredict. */ public UnaryCallSettings<RawPredictRequest, HttpBody> rawPredictSettings() { return rawPredictSettings; } /** Returns the object with the settings used for calls to streamRawPredict. */ public ServerStreamingCallSettings<StreamRawPredictRequest, HttpBody> streamRawPredictSettings() { return streamRawPredictSettings; } /** Returns the object with the settings used for calls to directPredict. */ public UnaryCallSettings<DirectPredictRequest, DirectPredictResponse> directPredictSettings() { return directPredictSettings; } /** Returns the object with the settings used for calls to directRawPredict. */ public UnaryCallSettings<DirectRawPredictRequest, DirectRawPredictResponse> directRawPredictSettings() { return directRawPredictSettings; } /** Returns the object with the settings used for calls to streamDirectPredict. */ public StreamingCallSettings<StreamDirectPredictRequest, StreamDirectPredictResponse> streamDirectPredictSettings() { return streamDirectPredictSettings; } /** Returns the object with the settings used for calls to streamDirectRawPredict. */ public StreamingCallSettings<StreamDirectRawPredictRequest, StreamDirectRawPredictResponse> streamDirectRawPredictSettings() { return streamDirectRawPredictSettings; } /** Returns the object with the settings used for calls to streamingPredict. */ public StreamingCallSettings<StreamingPredictRequest, StreamingPredictResponse> streamingPredictSettings() { return streamingPredictSettings; } /** Returns the object with the settings used for calls to serverStreamingPredict. */ public ServerStreamingCallSettings<StreamingPredictRequest, StreamingPredictResponse> serverStreamingPredictSettings() { return serverStreamingPredictSettings; } /** Returns the object with the settings used for calls to streamingRawPredict. */ public StreamingCallSettings<StreamingRawPredictRequest, StreamingRawPredictResponse> streamingRawPredictSettings() { return streamingRawPredictSettings; } /** Returns the object with the settings used for calls to explain. */ public UnaryCallSettings<ExplainRequest, ExplainResponse> explainSettings() { return explainSettings; } /** Returns the object with the settings used for calls to generateContent. */ public UnaryCallSettings<GenerateContentRequest, GenerateContentResponse> generateContentSettings() { return generateContentSettings; } /** Returns the object with the settings used for calls to streamGenerateContent. */ public ServerStreamingCallSettings<GenerateContentRequest, GenerateContentResponse> streamGenerateContentSettings() { return streamGenerateContentSettings; } /** Returns the object with the settings used for calls to listLocations. */ public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return listLocationsSettings; } /** Returns the object with the settings used for calls to getLocation. */ public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() { return getLocationSettings; } /** Returns the object with the settings used for calls to setIamPolicy. */ public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() { return setIamPolicySettings; } /** Returns the object with the settings used for calls to getIamPolicy. */ public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() { return getIamPolicySettings; } /** Returns the object with the settings used for calls to testIamPermissions. */ public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings() { return testIamPermissionsSettings; } public PredictionServiceStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcPredictionServiceStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "aiplatform"; } /** 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 "aiplatform.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "aiplatform.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 InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(PredictionServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** 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 PredictionServiceStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); predictSettings = settingsBuilder.predictSettings().build(); rawPredictSettings = settingsBuilder.rawPredictSettings().build(); streamRawPredictSettings = settingsBuilder.streamRawPredictSettings().build(); directPredictSettings = settingsBuilder.directPredictSettings().build(); directRawPredictSettings = settingsBuilder.directRawPredictSettings().build(); streamDirectPredictSettings = settingsBuilder.streamDirectPredictSettings().build(); streamDirectRawPredictSettings = settingsBuilder.streamDirectRawPredictSettings().build(); streamingPredictSettings = settingsBuilder.streamingPredictSettings().build(); serverStreamingPredictSettings = settingsBuilder.serverStreamingPredictSettings().build(); streamingRawPredictSettings = settingsBuilder.streamingRawPredictSettings().build(); explainSettings = settingsBuilder.explainSettings().build(); generateContentSettings = settingsBuilder.generateContentSettings().build(); streamGenerateContentSettings = settingsBuilder.streamGenerateContentSettings().build(); listLocationsSettings = settingsBuilder.listLocationsSettings().build(); getLocationSettings = settingsBuilder.getLocationSettings().build(); setIamPolicySettings = settingsBuilder.setIamPolicySettings().build(); getIamPolicySettings = settingsBuilder.getIamPolicySettings().build(); testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); } /** Builder for PredictionServiceStubSettings. */ public static class Builder extends StubSettings.Builder<PredictionServiceStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<PredictRequest, PredictResponse> predictSettings; private final UnaryCallSettings.Builder<RawPredictRequest, HttpBody> rawPredictSettings; private final ServerStreamingCallSettings.Builder<StreamRawPredictRequest, HttpBody> streamRawPredictSettings; private final UnaryCallSettings.Builder<DirectPredictRequest, DirectPredictResponse> directPredictSettings; private final UnaryCallSettings.Builder<DirectRawPredictRequest, DirectRawPredictResponse> directRawPredictSettings; private final StreamingCallSettings.Builder< StreamDirectPredictRequest, StreamDirectPredictResponse> streamDirectPredictSettings; private final StreamingCallSettings.Builder< StreamDirectRawPredictRequest, StreamDirectRawPredictResponse> streamDirectRawPredictSettings; private final StreamingCallSettings.Builder<StreamingPredictRequest, StreamingPredictResponse> streamingPredictSettings; private final ServerStreamingCallSettings.Builder< StreamingPredictRequest, StreamingPredictResponse> serverStreamingPredictSettings; private final StreamingCallSettings.Builder< StreamingRawPredictRequest, StreamingRawPredictResponse> streamingRawPredictSettings; private final UnaryCallSettings.Builder<ExplainRequest, ExplainResponse> explainSettings; private final UnaryCallSettings.Builder<GenerateContentRequest, GenerateContentResponse> generateContentSettings; private final ServerStreamingCallSettings.Builder< GenerateContentRequest, GenerateContentResponse> streamGenerateContentSettings; private final PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings; private final UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings; private final UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings; private final UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings; private final UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings; 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_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().setRpcTimeoutMultiplier(1.0).build(); definitions.put("no_retry_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); predictSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); rawPredictSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); streamRawPredictSettings = ServerStreamingCallSettings.newBuilder(); directPredictSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); directRawPredictSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); streamDirectPredictSettings = StreamingCallSettings.newBuilder(); streamDirectRawPredictSettings = StreamingCallSettings.newBuilder(); streamingPredictSettings = StreamingCallSettings.newBuilder(); serverStreamingPredictSettings = ServerStreamingCallSettings.newBuilder(); streamingRawPredictSettings = StreamingCallSettings.newBuilder(); explainSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); generateContentSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); streamGenerateContentSettings = ServerStreamingCallSettings.newBuilder(); listLocationsSettings = PagedCallSettings.newBuilder(LIST_LOCATIONS_PAGE_STR_FACT); getLocationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); setIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( predictSettings, rawPredictSettings, directPredictSettings, directRawPredictSettings, explainSettings, generateContentSettings, listLocationsSettings, getLocationSettings, setIamPolicySettings, getIamPolicySettings, testIamPermissionsSettings); initDefaults(this); } protected Builder(PredictionServiceStubSettings settings) { super(settings); predictSettings = settings.predictSettings.toBuilder(); rawPredictSettings = settings.rawPredictSettings.toBuilder(); streamRawPredictSettings = settings.streamRawPredictSettings.toBuilder(); directPredictSettings = settings.directPredictSettings.toBuilder(); directRawPredictSettings = settings.directRawPredictSettings.toBuilder(); streamDirectPredictSettings = settings.streamDirectPredictSettings.toBuilder(); streamDirectRawPredictSettings = settings.streamDirectRawPredictSettings.toBuilder(); streamingPredictSettings = settings.streamingPredictSettings.toBuilder(); serverStreamingPredictSettings = settings.serverStreamingPredictSettings.toBuilder(); streamingRawPredictSettings = settings.streamingRawPredictSettings.toBuilder(); explainSettings = settings.explainSettings.toBuilder(); generateContentSettings = settings.generateContentSettings.toBuilder(); streamGenerateContentSettings = settings.streamGenerateContentSettings.toBuilder(); listLocationsSettings = settings.listLocationsSettings.toBuilder(); getLocationSettings = settings.getLocationSettings.toBuilder(); setIamPolicySettings = settings.setIamPolicySettings.toBuilder(); getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( predictSettings, rawPredictSettings, directPredictSettings, directRawPredictSettings, explainSettings, generateContentSettings, listLocationsSettings, getLocationSettings, setIamPolicySettings, getIamPolicySettings, testIamPermissionsSettings); } 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 .predictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .rawPredictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .streamRawPredictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .directPredictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .directRawPredictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .serverStreamingPredictSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .explainSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .generateContentSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .streamGenerateContentSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .listLocationsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .getLocationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .setIamPolicySettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .getIamPolicySettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); builder .testIamPermissionsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params")); 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 predict. */ public UnaryCallSettings.Builder<PredictRequest, PredictResponse> predictSettings() { return predictSettings; } /** Returns the builder for the settings used for calls to rawPredict. */ public UnaryCallSettings.Builder<RawPredictRequest, HttpBody> rawPredictSettings() { return rawPredictSettings; } /** Returns the builder for the settings used for calls to streamRawPredict. */ public ServerStreamingCallSettings.Builder<StreamRawPredictRequest, HttpBody> streamRawPredictSettings() { return streamRawPredictSettings; } /** Returns the builder for the settings used for calls to directPredict. */ public UnaryCallSettings.Builder<DirectPredictRequest, DirectPredictResponse> directPredictSettings() { return directPredictSettings; } /** Returns the builder for the settings used for calls to directRawPredict. */ public UnaryCallSettings.Builder<DirectRawPredictRequest, DirectRawPredictResponse> directRawPredictSettings() { return directRawPredictSettings; } /** Returns the builder for the settings used for calls to streamDirectPredict. */ public StreamingCallSettings.Builder<StreamDirectPredictRequest, StreamDirectPredictResponse> streamDirectPredictSettings() { return streamDirectPredictSettings; } /** Returns the builder for the settings used for calls to streamDirectRawPredict. */ public StreamingCallSettings.Builder< StreamDirectRawPredictRequest, StreamDirectRawPredictResponse> streamDirectRawPredictSettings() { return streamDirectRawPredictSettings; } /** Returns the builder for the settings used for calls to streamingPredict. */ public StreamingCallSettings.Builder<StreamingPredictRequest, StreamingPredictResponse> streamingPredictSettings() { return streamingPredictSettings; } /** Returns the builder for the settings used for calls to serverStreamingPredict. */ public ServerStreamingCallSettings.Builder<StreamingPredictRequest, StreamingPredictResponse> serverStreamingPredictSettings() { return serverStreamingPredictSettings; } /** Returns the builder for the settings used for calls to streamingRawPredict. */ public StreamingCallSettings.Builder<StreamingRawPredictRequest, StreamingRawPredictResponse> streamingRawPredictSettings() { return streamingRawPredictSettings; } /** Returns the builder for the settings used for calls to explain. */ public UnaryCallSettings.Builder<ExplainRequest, ExplainResponse> explainSettings() { return explainSettings; } /** Returns the builder for the settings used for calls to generateContent. */ public UnaryCallSettings.Builder<GenerateContentRequest, GenerateContentResponse> generateContentSettings() { return generateContentSettings; } /** Returns the builder for the settings used for calls to streamGenerateContent. */ public ServerStreamingCallSettings.Builder<GenerateContentRequest, GenerateContentResponse> streamGenerateContentSettings() { return streamGenerateContentSettings; } /** Returns the builder for the settings used for calls to listLocations. */ public PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return listLocationsSettings; } /** Returns the builder for the settings used for calls to getLocation. */ public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() { return getLocationSettings; } /** Returns the builder for the settings used for calls to setIamPolicy. */ public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() { return setIamPolicySettings; } /** Returns the builder for the settings used for calls to getIamPolicy. */ public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() { return getIamPolicySettings; } /** Returns the builder for the settings used for calls to testIamPermissions. */ public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsSettings() { return testIamPermissionsSettings; } @Override public PredictionServiceStubSettings build() throws IOException { return new PredictionServiceStubSettings(this); } } }
googleapis/google-cloud-java
35,304
java-area120-tables/proto-google-area120-tables-v1alpha1/src/main/java/com/google/area120/tables/v1alpha1/ListTablesResponse.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/area120/tables/v1alpha1/tables.proto // Protobuf Java Version: 3.25.8 package com.google.area120.tables.v1alpha1; /** * * * <pre> * Response message for TablesService.ListTables. * </pre> * * Protobuf type {@code google.area120.tables.v1alpha1.ListTablesResponse} */ public final class ListTablesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.area120.tables.v1alpha1.ListTablesResponse) ListTablesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListTablesResponse.newBuilder() to construct. private ListTablesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListTablesResponse() { tables_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListTablesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.area120.tables.v1alpha1.TablesProto .internal_static_google_area120_tables_v1alpha1_ListTablesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.area120.tables.v1alpha1.TablesProto .internal_static_google_area120_tables_v1alpha1_ListTablesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.area120.tables.v1alpha1.ListTablesResponse.class, com.google.area120.tables.v1alpha1.ListTablesResponse.Builder.class); } public static final int TABLES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.area120.tables.v1alpha1.Table> tables_; /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ @java.lang.Override public java.util.List<com.google.area120.tables.v1alpha1.Table> getTablesList() { return tables_; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.area120.tables.v1alpha1.TableOrBuilder> getTablesOrBuilderList() { return tables_; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ @java.lang.Override public int getTablesCount() { return tables_.size(); } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ @java.lang.Override public com.google.area120.tables.v1alpha1.Table getTables(int index) { return tables_.get(index); } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ @java.lang.Override public com.google.area120.tables.v1alpha1.TableOrBuilder getTablesOrBuilder(int index) { return tables_.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 empty, 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 empty, 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 < tables_.size(); i++) { output.writeMessage(1, tables_.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 < tables_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tables_.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.area120.tables.v1alpha1.ListTablesResponse)) { return super.equals(obj); } com.google.area120.tables.v1alpha1.ListTablesResponse other = (com.google.area120.tables.v1alpha1.ListTablesResponse) obj; if (!getTablesList().equals(other.getTablesList())) 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 (getTablesCount() > 0) { hash = (37 * hash) + TABLES_FIELD_NUMBER; hash = (53 * hash) + getTablesList().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.area120.tables.v1alpha1.ListTablesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.area120.tables.v1alpha1.ListTablesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.area120.tables.v1alpha1.ListTablesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.area120.tables.v1alpha1.ListTablesResponse 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.area120.tables.v1alpha1.ListTablesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.area120.tables.v1alpha1.ListTablesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.area120.tables.v1alpha1.ListTablesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.area120.tables.v1alpha1.ListTablesResponse 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.area120.tables.v1alpha1.ListTablesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.area120.tables.v1alpha1.ListTablesResponse 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.area120.tables.v1alpha1.ListTablesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.area120.tables.v1alpha1.ListTablesResponse 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.area120.tables.v1alpha1.ListTablesResponse 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 TablesService.ListTables. * </pre> * * Protobuf type {@code google.area120.tables.v1alpha1.ListTablesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.area120.tables.v1alpha1.ListTablesResponse) com.google.area120.tables.v1alpha1.ListTablesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.area120.tables.v1alpha1.TablesProto .internal_static_google_area120_tables_v1alpha1_ListTablesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.area120.tables.v1alpha1.TablesProto .internal_static_google_area120_tables_v1alpha1_ListTablesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.area120.tables.v1alpha1.ListTablesResponse.class, com.google.area120.tables.v1alpha1.ListTablesResponse.Builder.class); } // Construct using com.google.area120.tables.v1alpha1.ListTablesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (tablesBuilder_ == null) { tables_ = java.util.Collections.emptyList(); } else { tables_ = null; tablesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.area120.tables.v1alpha1.TablesProto .internal_static_google_area120_tables_v1alpha1_ListTablesResponse_descriptor; } @java.lang.Override public com.google.area120.tables.v1alpha1.ListTablesResponse getDefaultInstanceForType() { return com.google.area120.tables.v1alpha1.ListTablesResponse.getDefaultInstance(); } @java.lang.Override public com.google.area120.tables.v1alpha1.ListTablesResponse build() { com.google.area120.tables.v1alpha1.ListTablesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.area120.tables.v1alpha1.ListTablesResponse buildPartial() { com.google.area120.tables.v1alpha1.ListTablesResponse result = new com.google.area120.tables.v1alpha1.ListTablesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.area120.tables.v1alpha1.ListTablesResponse result) { if (tablesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { tables_ = java.util.Collections.unmodifiableList(tables_); bitField0_ = (bitField0_ & ~0x00000001); } result.tables_ = tables_; } else { result.tables_ = tablesBuilder_.build(); } } private void buildPartial0(com.google.area120.tables.v1alpha1.ListTablesResponse 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.area120.tables.v1alpha1.ListTablesResponse) { return mergeFrom((com.google.area120.tables.v1alpha1.ListTablesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.area120.tables.v1alpha1.ListTablesResponse other) { if (other == com.google.area120.tables.v1alpha1.ListTablesResponse.getDefaultInstance()) return this; if (tablesBuilder_ == null) { if (!other.tables_.isEmpty()) { if (tables_.isEmpty()) { tables_ = other.tables_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTablesIsMutable(); tables_.addAll(other.tables_); } onChanged(); } } else { if (!other.tables_.isEmpty()) { if (tablesBuilder_.isEmpty()) { tablesBuilder_.dispose(); tablesBuilder_ = null; tables_ = other.tables_; bitField0_ = (bitField0_ & ~0x00000001); tablesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTablesFieldBuilder() : null; } else { tablesBuilder_.addAllMessages(other.tables_); } } } 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.area120.tables.v1alpha1.Table m = input.readMessage( com.google.area120.tables.v1alpha1.Table.parser(), extensionRegistry); if (tablesBuilder_ == null) { ensureTablesIsMutable(); tables_.add(m); } else { tablesBuilder_.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.area120.tables.v1alpha1.Table> tables_ = java.util.Collections.emptyList(); private void ensureTablesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tables_ = new java.util.ArrayList<com.google.area120.tables.v1alpha1.Table>(tables_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.area120.tables.v1alpha1.Table, com.google.area120.tables.v1alpha1.Table.Builder, com.google.area120.tables.v1alpha1.TableOrBuilder> tablesBuilder_; /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public java.util.List<com.google.area120.tables.v1alpha1.Table> getTablesList() { if (tablesBuilder_ == null) { return java.util.Collections.unmodifiableList(tables_); } else { return tablesBuilder_.getMessageList(); } } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public int getTablesCount() { if (tablesBuilder_ == null) { return tables_.size(); } else { return tablesBuilder_.getCount(); } } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public com.google.area120.tables.v1alpha1.Table getTables(int index) { if (tablesBuilder_ == null) { return tables_.get(index); } else { return tablesBuilder_.getMessage(index); } } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder setTables(int index, com.google.area120.tables.v1alpha1.Table value) { if (tablesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTablesIsMutable(); tables_.set(index, value); onChanged(); } else { tablesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder setTables( int index, com.google.area120.tables.v1alpha1.Table.Builder builderForValue) { if (tablesBuilder_ == null) { ensureTablesIsMutable(); tables_.set(index, builderForValue.build()); onChanged(); } else { tablesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder addTables(com.google.area120.tables.v1alpha1.Table value) { if (tablesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTablesIsMutable(); tables_.add(value); onChanged(); } else { tablesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder addTables(int index, com.google.area120.tables.v1alpha1.Table value) { if (tablesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTablesIsMutable(); tables_.add(index, value); onChanged(); } else { tablesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder addTables(com.google.area120.tables.v1alpha1.Table.Builder builderForValue) { if (tablesBuilder_ == null) { ensureTablesIsMutable(); tables_.add(builderForValue.build()); onChanged(); } else { tablesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder addTables( int index, com.google.area120.tables.v1alpha1.Table.Builder builderForValue) { if (tablesBuilder_ == null) { ensureTablesIsMutable(); tables_.add(index, builderForValue.build()); onChanged(); } else { tablesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder addAllTables( java.lang.Iterable<? extends com.google.area120.tables.v1alpha1.Table> values) { if (tablesBuilder_ == null) { ensureTablesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tables_); onChanged(); } else { tablesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder clearTables() { if (tablesBuilder_ == null) { tables_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { tablesBuilder_.clear(); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public Builder removeTables(int index) { if (tablesBuilder_ == null) { ensureTablesIsMutable(); tables_.remove(index); onChanged(); } else { tablesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public com.google.area120.tables.v1alpha1.Table.Builder getTablesBuilder(int index) { return getTablesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public com.google.area120.tables.v1alpha1.TableOrBuilder getTablesOrBuilder(int index) { if (tablesBuilder_ == null) { return tables_.get(index); } else { return tablesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public java.util.List<? extends com.google.area120.tables.v1alpha1.TableOrBuilder> getTablesOrBuilderList() { if (tablesBuilder_ != null) { return tablesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tables_); } } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public com.google.area120.tables.v1alpha1.Table.Builder addTablesBuilder() { return getTablesFieldBuilder() .addBuilder(com.google.area120.tables.v1alpha1.Table.getDefaultInstance()); } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public com.google.area120.tables.v1alpha1.Table.Builder addTablesBuilder(int index) { return getTablesFieldBuilder() .addBuilder(index, com.google.area120.tables.v1alpha1.Table.getDefaultInstance()); } /** * * * <pre> * The list of tables. * </pre> * * <code>repeated .google.area120.tables.v1alpha1.Table tables = 1;</code> */ public java.util.List<com.google.area120.tables.v1alpha1.Table.Builder> getTablesBuilderList() { return getTablesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.area120.tables.v1alpha1.Table, com.google.area120.tables.v1alpha1.Table.Builder, com.google.area120.tables.v1alpha1.TableOrBuilder> getTablesFieldBuilder() { if (tablesBuilder_ == null) { tablesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.area120.tables.v1alpha1.Table, com.google.area120.tables.v1alpha1.Table.Builder, com.google.area120.tables.v1alpha1.TableOrBuilder>( tables_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); tables_ = null; } return tablesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is empty, 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 empty, 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 empty, 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 empty, 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 empty, 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.area120.tables.v1alpha1.ListTablesResponse) } // @@protoc_insertion_point(class_scope:google.area120.tables.v1alpha1.ListTablesResponse) private static final com.google.area120.tables.v1alpha1.ListTablesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.area120.tables.v1alpha1.ListTablesResponse(); } public static com.google.area120.tables.v1alpha1.ListTablesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListTablesResponse> PARSER = new com.google.protobuf.AbstractParser<ListTablesResponse>() { @java.lang.Override public ListTablesResponse 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<ListTablesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListTablesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.area120.tables.v1alpha1.ListTablesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ranger
35,566
security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ranger.security.handler; import org.apache.ranger.authentication.unix.jaas.RoleUserAuthorityGranter; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.util.Pbkdf2PasswordEncoderCust; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProvider; import org.springframework.security.authentication.jaas.memory.InMemoryConfiguration; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.ldap.DefaultSpringSecurityContextSource; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.authentication.LdapAuthenticator; import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator; import org.springframework.security.provisioning.JdbcUserDetailsManager; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class RangerAuthenticationProvider implements AuthenticationProvider { private static final Logger logger = LoggerFactory.getLogger(RangerAuthenticationProvider.class); private final boolean isFipsEnabled; protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @Autowired UserMgr userMgr; @Autowired SessionMgr sessionMgr; @Autowired @Qualifier("userService") private JdbcUserDetailsManager userDetailsService; private String rangerAuthenticationMethod; private LdapAuthenticator authenticator; private boolean ssoEnabled; public RangerAuthenticationProvider() { this.isFipsEnabled = RangerAdminConfig.getInstance().isFipsEnabled(); } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (isSsoEnabled()) { if (authentication != null) { authentication = getSSOAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } } } else { String sha256PasswordUpdateDisable = PropertiesUtil.getProperty("ranger.sha256Password.update.disable", "false"); if (rangerAuthenticationMethod == null) { rangerAuthenticationMethod = "NONE"; } if (authentication != null) { if ("LDAP".equalsIgnoreCase(rangerAuthenticationMethod)) { authentication = getLdapAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } else { authentication = getLdapBindAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } } } else if ("ACTIVE_DIRECTORY".equalsIgnoreCase(rangerAuthenticationMethod)) { authentication = getADBindAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } else { authentication = getADAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } } } else if ("UNIX".equalsIgnoreCase(rangerAuthenticationMethod)) { boolean isPAMAuthEnabled = PropertiesUtil.getBooleanProperty("ranger.pam.authentication.enabled", false); authentication = (isPAMAuthEnabled ? getPamAuthentication(authentication) : getUnixAuthentication(authentication)); if (authentication != null && authentication.isAuthenticated()) { return authentication; } } else if ("PAM".equalsIgnoreCase(rangerAuthenticationMethod)) { authentication = getPamAuthentication(authentication); if (authentication != null && authentication.isAuthenticated()) { return authentication; } } // Following are JDBC if (authentication != null && authentication.getName() != null && sessionMgr.isLoginIdLocked(authentication.getName())) { logger.debug("Failed to authenticate since user account is locked"); throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (this.isFipsEnabled) { try { authentication = getJDBCAuthentication(authentication, ""); } catch (Exception e) { logger.error("JDBC Authentication failure: ", e); throw e; } return authentication; } String encoder = "SHA256"; try { authentication = getJDBCAuthentication(authentication, encoder); } catch (Exception e) { logger.debug("JDBC Authentication failure: ", e); } if (authentication != null && authentication.isAuthenticated()) { return authentication; } if (authentication != null && !authentication.isAuthenticated()) { logger.info("Authentication with SHA-256 failed. Now trying with MD5."); encoder = "MD5"; String userName = authentication.getName(); String userPassword = null; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } try { authentication = getJDBCAuthentication(authentication, encoder); } catch (Exception e) { throw e; } if (authentication != null && authentication.isAuthenticated()) { if ("false".equalsIgnoreCase(sha256PasswordUpdateDisable)) { userMgr.updatePasswordInSHA256(userName, userPassword, false); } } return authentication; } return authentication; } } return authentication; } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } public Authentication getADAuthentication(Authentication authentication) { try { String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", ""); String rangerADDomain = PropertiesUtil.getProperty("ranger.ldap.ad.domain", ""); String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(rangerADDomain, rangerADURL); adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true); adAuthenticationProvider.setUseAuthenticationRequestCredentials(true); adAuthenticationProvider.setSearchFilter(rangerLdapUserSearchFilter); // Grab the user-name and password out of the authentication object. String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } // getting user authenticated if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = adAuthenticationProvider.authenticate(finalAuthentication); } return authentication; } catch (Exception e) { logger.error("AD Authentication Failed:", e); } return authentication; } public Authentication getPamAuthentication(Authentication authentication) { try { String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); String loginModuleName = "org.apache.ranger.authentication.unix.jaas.PamLoginModule"; LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; Map<String, String> options = PropertiesUtil.getPropertiesMap(); if (!options.containsKey("ranger.pam.service")) { options.put("ranger.pam.service", "ranger-admin"); } AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(loginModuleName, controlFlag, options); AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] {appConfigurationEntry}; Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<>(); appConfigurationEntriesOptions.put("SPRINGSECURITY", appConfigurationEntries); Configuration configuration = new InMemoryConfiguration(appConfigurationEntriesOptions); jaasAuthenticationProvider.setConfiguration(configuration); RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] {authorityGranter}; jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); jaasAuthenticationProvider.afterPropertiesSet(); String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } // getting user authenticated if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = jaasAuthenticationProvider.authenticate(finalAuthentication); authentication = getAuthenticationWithGrantedAuthority(authentication); } return authentication; } catch (Exception e) { logger.debug("Pam Authentication Failed:", e); } return authentication; } public Authentication getUnixAuthentication(Authentication authentication) { try { String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule"; LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; Map<String, String> options = PropertiesUtil.getPropertiesMap(); AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(loginModuleName, controlFlag, options); AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] {appConfigurationEntry}; Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<>(); appConfigurationEntriesOptions.put("SPRINGSECURITY", appConfigurationEntries); Configuration configuration = new InMemoryConfiguration(appConfigurationEntriesOptions); jaasAuthenticationProvider.setConfiguration(configuration); RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] {authorityGranter}; jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); jaasAuthenticationProvider.afterPropertiesSet(); String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } // getting user authenticated if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = jaasAuthenticationProvider.authenticate(finalAuthentication); authentication = getAuthenticationWithGrantedAuthority(authentication); } return authentication; } catch (Exception e) { logger.debug("Unix Authentication Failed:", e); } return authentication; } public String getRangerAuthenticationMethod() { return rangerAuthenticationMethod; } public void setRangerAuthenticationMethod(String rangerAuthenticationMethod) { this.rangerAuthenticationMethod = rangerAuthenticationMethod; } public LdapAuthenticator getAuthenticator() { return authenticator; } public void setAuthenticator(LdapAuthenticator authenticator) { this.authenticator = authenticator; } public Authentication getAuthenticationWithGrantedAuthority(Authentication authentication) { UsernamePasswordAuthenticationToken result; if (authentication != null && authentication.isAuthenticated()) { final List<GrantedAuthority> grantedAuths = getAuthorities(authentication.getName()); final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuths); result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuths); result.setDetails(authentication.getDetails()); return result; } return authentication; } /** * @return the ssoEnabled */ public boolean isSsoEnabled() { return ssoEnabled; } /** * @param ssoEnabled the ssoEnabled to set */ public void setSsoEnabled(boolean ssoEnabled) { this.ssoEnabled = ssoEnabled; } private Authentication getLdapAuthentication(Authentication authentication) { try { // getting ldap settings String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", ""); String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", ""); String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", ""); String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", ""); String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", ""); String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); // taking the user-name and password from the authentication // object. String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } // populating LDAP context source with LDAP URL and user-DN-pattern LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerLdapURL); if (rangerIsStartTlsEnabled) { ldapContextSource.setPooled(false); ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); } ldapContextSource.setCacheEnvironmentProperties(false); ldapContextSource.setAnonymousReadOnly(true); // Creating BindAuthenticator using Ldap Context Source. BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern }; String[] userDnPatterns = rangerLdapUserDNPattern.split(";"); bindAuthenticator.setUserDnPatterns(userDnPatterns); LdapAuthenticationProvider ldapAuthenticationProvider; if (!StringUtil.isEmpty(rangerLdapGroupSearchBase) && !StringUtil.isEmpty(rangerLdapGroupSearchFilter)) { // Creating LDAP authorities populator using Ldap context source and // Ldap group search base. // populating LDAP authorities populator with group search // base,group role attribute, group search filter. DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase); defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); // Creating Ldap authentication provider using BindAuthenticator and Ldap authentication populator ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator); } else { ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); } // getting user authenticated if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); authentication = getAuthenticationWithGrantedAuthority(authentication); } return authentication; } catch (Exception e) { logger.error("LDAP Authentication Failed:", e); } return authentication; } private Authentication getADBindAuthentication(Authentication authentication) { try { String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", ""); String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", ""); String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", ""); String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", ""); String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow"); String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL); ldapContextSource.setUserDn(rangerADBindDN); ldapContextSource.setPassword(rangerADBindPassword); ldapContextSource.setReferral(rangerLdapReferral); ldapContextSource.setCacheEnvironmentProperties(true); ldapContextSource.setAnonymousReadOnly(false); ldapContextSource.setPooled(true); if (rangerIsStartTlsEnabled) { ldapContextSource.setPooled(false); ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); } ldapContextSource.afterPropertiesSet(); //String searchFilter="(sAMAccountName={0})"; if (rangerLdapUserSearchFilter == null || rangerLdapUserSearchFilter.trim().isEmpty()) { rangerLdapUserSearchFilter = "(sAMAccountName={0})"; } FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter, ldapContextSource); userSearch.setSearchSubtree(true); BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); bindAuthenticator.setUserSearch(userSearch); bindAuthenticator.afterPropertiesSet(); LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); authentication = getAuthenticationWithGrantedAuthority(authentication); } return authentication; } catch (Exception e) { logger.error("AD bind Authentication Failed:", e); } return authentication; } private Authentication getLdapBindAuthentication(Authentication authentication) { try { String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", ""); String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", ""); String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", ""); String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", ""); String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", ""); String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); String rangerLdapBase = PropertiesUtil.getProperty("ranger.ldap.base.dn", ""); String rangerLdapBindDN = PropertiesUtil.getProperty("ranger.ldap.bind.dn", ""); String rangerLdapBindPassword = PropertiesUtil.getProperty("ranger.ldap.bind.password", ""); String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.referral", "follow"); String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.user.searchfilter", "(uid={0})"); boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); String userName = authentication.getName(); String userPassword = ""; if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerLdapURL); ldapContextSource.setUserDn(rangerLdapBindDN); ldapContextSource.setPassword(rangerLdapBindPassword); ldapContextSource.setReferral(rangerLdapReferral); ldapContextSource.setCacheEnvironmentProperties(false); ldapContextSource.setAnonymousReadOnly(false); ldapContextSource.setPooled(true); if (rangerIsStartTlsEnabled) { ldapContextSource.setPooled(false); ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); } ldapContextSource.afterPropertiesSet(); DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase); defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); //String searchFilter="(uid={0})"; if (rangerLdapUserSearchFilter == null || rangerLdapUserSearchFilter.trim().isEmpty()) { rangerLdapUserSearchFilter = "(uid={0})"; } FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(rangerLdapBase, rangerLdapUserSearchFilter, ldapContextSource); userSearch.setSearchSubtree(true); BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); bindAuthenticator.setUserSearch(userSearch); String[] userDnPatterns = new String[] {rangerLdapUserDNPattern}; bindAuthenticator.setUserDnPatterns(userDnPatterns); bindAuthenticator.afterPropertiesSet(); LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator); if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); authentication = getAuthenticationWithGrantedAuthority(authentication); } return authentication; } catch (Exception e) { logger.error("LDAP bind Authentication Failed:", e); } return authentication; } private Authentication getJDBCAuthentication(Authentication authentication, String encoder) throws AuthenticationException { try { DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider(); authenticator.setUserDetailsService(userDetailsService); if (this.isFipsEnabled) { if (authentication != null && authentication.getCredentials() != null && !authentication.isAuthenticated()) { Pbkdf2PasswordEncoderCust passwordEncoder = new Pbkdf2PasswordEncoderCust(authentication.getName()); passwordEncoder.setEncodeHashAsBase64(true); authenticator.setPasswordEncoder(passwordEncoder); } } else { if ("SHA256".equalsIgnoreCase(encoder) && authentication != null) { authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "SHA-256")); } else if ("MD5".equalsIgnoreCase(encoder) && authentication != null) { authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "MD5")); } } String userName = ""; String userPassword = ""; if (authentication != null) { userName = authentication.getName(); if (authentication.getCredentials() != null) { userPassword = authentication.getCredentials().toString(); } } String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, userPassword, grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); authentication = authenticator.authenticate(finalAuthentication); return authentication; } else { if (authentication != null && !authentication.isAuthenticated()) { throw new BadCredentialsException("Bad credentials"); } } } catch (Exception e) { throw e; } catch (Throwable t) { throw new BadCredentialsException("Bad credentials", t); } return authentication; } private List<GrantedAuthority> getAuthorities(String username) { Collection<String> roleList = userMgr.getRolesByLoginId(username); final List<GrantedAuthority> grantedAuths = new ArrayList<>(); for (String role : roleList) { grantedAuths.add(new SimpleGrantedAuthority(role)); } return grantedAuths; } private Authentication getSSOAuthentication(Authentication authentication) throws AuthenticationException { return authentication; } }
googleapis/google-api-java-client-services
35,340
clients/google-api-services-compute/beta/1.31.0/com/google/api/services/compute/model/Operation.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Represents an Operation resource. Google Compute Engine has three Operation resources: * * [Global](/compute/docs/reference/rest/beta/globalOperations) * * [Regional](/compute/docs/reference/rest/beta/regionOperations) * * [Zonal](/compute/docs/reference/rest/beta/zoneOperations) You can use an operation resource to * manage asynchronous API requests. For more information, read Handling API responses. Operations * can be global, regional or zonal. - For global operations, use the `globalOperations` resource. - * For regional operations, use the `regionOperations` resource. - For zonal operations, use the * `zonalOperations` resource. For more information, read Global, Regional, and Zonal Resources. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Operation extends com.google.api.client.json.GenericJson { /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String clientOperationId; /** * [Deprecated] This field is deprecated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creationTimestamp; /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String endTime; /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private Error error; /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String httpErrorMessage; /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer httpErrorStatusCode; /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger id; /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String insertTime; /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * [Output Only] Name of the operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String operationGroupId; /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String operationType; /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer progress; /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * [Output Only] Server-defined URL for the resource. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String selfLink; /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String startTime; /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String status; /** * [Output Only] An optional textual description of the current status of the operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String statusMessage; /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.math.BigInteger targetId; /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String targetLink; /** * [Output Only] User who requested the operation, for example: `user@example.com`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String user; /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Warnings> warnings; static { // hack to force ProGuard to consider Warnings 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(Warnings.class); } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String zone; /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @return value or {@code null} for none */ public java.lang.String getClientOperationId() { return clientOperationId; } /** * [Output Only] The value of `requestId` if you provided it in the request. Not present * otherwise. * @param clientOperationId clientOperationId or {@code null} for none */ public Operation setClientOperationId(java.lang.String clientOperationId) { this.clientOperationId = clientOperationId; return this; } /** * [Deprecated] This field is deprecated. * @return value or {@code null} for none */ public java.lang.String getCreationTimestamp() { return creationTimestamp; } /** * [Deprecated] This field is deprecated. * @param creationTimestamp creationTimestamp or {@code null} for none */ public Operation setCreationTimestamp(java.lang.String creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * [Output Only] A textual description of the operation, which is set when the operation is * created. * @param description description or {@code null} for none */ public Operation setDescription(java.lang.String description) { this.description = description; return this; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getEndTime() { return endTime; } /** * [Output Only] The time that this operation was completed. This value is in RFC3339 text format. * @param endTime endTime or {@code null} for none */ public Operation setEndTime(java.lang.String endTime) { this.endTime = endTime; return this; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @return value or {@code null} for none */ public Error getError() { return error; } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. * @param error error or {@code null} for none */ public Operation setError(Error error) { this.error = error; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * @return value or {@code null} for none */ public java.lang.String getHttpErrorMessage() { return httpErrorMessage; } /** * [Output Only] If the operation fails, this field contains the HTTP error message that was * returned, such as `NOT FOUND`. * @param httpErrorMessage httpErrorMessage or {@code null} for none */ public Operation setHttpErrorMessage(java.lang.String httpErrorMessage) { this.httpErrorMessage = httpErrorMessage; return this; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * @return value or {@code null} for none */ public java.lang.Integer getHttpErrorStatusCode() { return httpErrorStatusCode; } /** * [Output Only] If the operation fails, this field contains the HTTP error status code that was * returned. For example, a `404` means the resource was not found. * @param httpErrorStatusCode httpErrorStatusCode or {@code null} for none */ public Operation setHttpErrorStatusCode(java.lang.Integer httpErrorStatusCode) { this.httpErrorStatusCode = httpErrorStatusCode; return this; } /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * @return value or {@code null} for none */ public java.math.BigInteger getId() { return id; } /** * [Output Only] The unique identifier for the operation. This identifier is defined by the * server. * @param id id or {@code null} for none */ public Operation setId(java.math.BigInteger id) { this.id = id; return this; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @return value or {@code null} for none */ public java.lang.String getInsertTime() { return insertTime; } /** * [Output Only] The time that this operation was requested. This value is in RFC3339 text format. * @param insertTime insertTime or {@code null} for none */ public Operation setInsertTime(java.lang.String insertTime) { this.insertTime = insertTime; return this; } /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * [Output Only] Type of the resource. Always `compute#operation` for Operation resources. * @param kind kind or {@code null} for none */ public Operation setKind(java.lang.String kind) { this.kind = kind; return this; } /** * [Output Only] Name of the operation. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * [Output Only] Name of the operation. * @param name name or {@code null} for none */ public Operation setName(java.lang.String name) { this.name = name; return this; } /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * @return value or {@code null} for none */ public java.lang.String getOperationGroupId() { return operationGroupId; } /** * [Output Only] An ID that represents a group of operations, such as when a group of operations * results from a `bulkInsert` API request. * @param operationGroupId operationGroupId or {@code null} for none */ public Operation setOperationGroupId(java.lang.String operationGroupId) { this.operationGroupId = operationGroupId; return this; } /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * @return value or {@code null} for none */ public java.lang.String getOperationType() { return operationType; } /** * [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. * @param operationType operationType or {@code null} for none */ public Operation setOperationType(java.lang.String operationType) { this.operationType = operationType; return this; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @return value or {@code null} for none */ public java.lang.Integer getProgress() { return progress; } /** * [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement * that this be linear or support any granularity of operations. This should not be used to guess * when the operation will be complete. This number should monotonically increase as the operation * progresses. * @param progress progress or {@code null} for none */ public Operation setProgress(java.lang.Integer progress) { this.progress = progress; return this; } /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * [Output Only] The URL of the region where the operation resides. Only applicable when * performing regional operations. * @param region region or {@code null} for none */ public Operation setRegion(java.lang.String region) { this.region = region; return this; } /** * [Output Only] Server-defined URL for the resource. * @return value or {@code null} for none */ public java.lang.String getSelfLink() { return selfLink; } /** * [Output Only] Server-defined URL for the resource. * @param selfLink selfLink or {@code null} for none */ public Operation setSelfLink(java.lang.String selfLink) { this.selfLink = selfLink; return this; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @return value or {@code null} for none */ public java.lang.String getStartTime() { return startTime; } /** * [Output Only] The time that this operation was started by the server. This value is in RFC3339 * text format. * @param startTime startTime or {@code null} for none */ public Operation setStartTime(java.lang.String startTime) { this.startTime = startTime; return this; } /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * @return value or {@code null} for none */ public java.lang.String getStatus() { return status; } /** * [Output Only] The status of the operation, which can be one of the following: `PENDING`, * `RUNNING`, or `DONE`. * @param status status or {@code null} for none */ public Operation setStatus(java.lang.String status) { this.status = status; return this; } /** * [Output Only] An optional textual description of the current status of the operation. * @return value or {@code null} for none */ public java.lang.String getStatusMessage() { return statusMessage; } /** * [Output Only] An optional textual description of the current status of the operation. * @param statusMessage statusMessage or {@code null} for none */ public Operation setStatusMessage(java.lang.String statusMessage) { this.statusMessage = statusMessage; return this; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @return value or {@code null} for none */ public java.math.BigInteger getTargetId() { return targetId; } /** * [Output Only] The unique target ID, which identifies a specific incarnation of the target * resource. * @param targetId targetId or {@code null} for none */ public Operation setTargetId(java.math.BigInteger targetId) { this.targetId = targetId; return this; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @return value or {@code null} for none */ public java.lang.String getTargetLink() { return targetLink; } /** * [Output Only] The URL of the resource that the operation modifies. For operations related to * creating a snapshot, this points to the persistent disk that the snapshot was created from. * @param targetLink targetLink or {@code null} for none */ public Operation setTargetLink(java.lang.String targetLink) { this.targetLink = targetLink; return this; } /** * [Output Only] User who requested the operation, for example: `user@example.com`. * @return value or {@code null} for none */ public java.lang.String getUser() { return user; } /** * [Output Only] User who requested the operation, for example: `user@example.com`. * @param user user or {@code null} for none */ public Operation setUser(java.lang.String user) { this.user = user; return this; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @return value or {@code null} for none */ public java.util.List<Warnings> getWarnings() { return warnings; } /** * [Output Only] If warning messages are generated during processing of the operation, this field * will be populated. * @param warnings warnings or {@code null} for none */ public Operation setWarnings(java.util.List<Warnings> warnings) { this.warnings = warnings; return this; } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * @return value or {@code null} for none */ public java.lang.String getZone() { return zone; } /** * [Output Only] The URL of the zone where the operation resides. Only applicable when performing * per-zone operations. * @param zone zone or {@code null} for none */ public Operation setZone(java.lang.String zone) { this.zone = zone; return this; } @Override public Operation set(String fieldName, Object value) { return (Operation) super.set(fieldName, value); } @Override public Operation clone() { return (Operation) super.clone(); } /** * [Output Only] If errors are generated during processing of the operation, this field will be * populated. */ public static final class Error extends com.google.api.client.json.GenericJson { /** * [Output Only] The array of errors encountered while processing this operation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Errors> errors; static { // hack to force ProGuard to consider Errors 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(Errors.class); } /** * [Output Only] The array of errors encountered while processing this operation. * @return value or {@code null} for none */ public java.util.List<Errors> getErrors() { return errors; } /** * [Output Only] The array of errors encountered while processing this operation. * @param errors errors or {@code null} for none */ public Error setErrors(java.util.List<Errors> errors) { this.errors = errors; return this; } @Override public Error set(String fieldName, Object value) { return (Error) super.set(fieldName, value); } @Override public Error clone() { return (Error) super.clone(); } /** * Model definition for OperationErrorErrors. */ public static final class Errors extends com.google.api.client.json.GenericJson { /** * [Output Only] The error type identifier for this error. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ErrorDetails> errorDetails; static { // hack to force ProGuard to consider ErrorDetails 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(ErrorDetails.class); } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String location; /** * [Output Only] An optional, human-readable error message. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] The error type identifier for this error. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] The error type identifier for this error. * @param code code or {@code null} for none */ public Errors setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * @return value or {@code null} for none */ public java.util.List<ErrorDetails> getErrorDetails() { return errorDetails; } /** * [Output Only] An optional list of messages that contain the error details. There is a set of * defined message types to use for providing details.The syntax depends on the error code. For * example, QuotaExceededInfo will have details when the error code is QUOTA_EXCEEDED. * @param errorDetails errorDetails or {@code null} for none */ public Errors setErrorDetails(java.util.List<ErrorDetails> errorDetails) { this.errorDetails = errorDetails; return this; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @return value or {@code null} for none */ public java.lang.String getLocation() { return location; } /** * [Output Only] Indicates the field in the request that caused the error. This property is * optional. * @param location location or {@code null} for none */ public Errors setLocation(java.lang.String location) { this.location = location; return this; } /** * [Output Only] An optional, human-readable error message. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] An optional, human-readable error message. * @param message message or {@code null} for none */ public Errors setMessage(java.lang.String message) { this.message = message; return this; } @Override public Errors set(String fieldName, Object value) { return (Errors) super.set(fieldName, value); } @Override public Errors clone() { return (Errors) super.clone(); } /** * Model definition for OperationErrorErrorsErrorDetails. */ public static final class ErrorDetails extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private ErrorInfo errorInfo; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private Help help; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private LocalizedMessage localizedMessage; /** * @return value or {@code null} for none */ public ErrorInfo getErrorInfo() { return errorInfo; } /** * @param errorInfo errorInfo or {@code null} for none */ public ErrorDetails setErrorInfo(ErrorInfo errorInfo) { this.errorInfo = errorInfo; return this; } /** * @return value or {@code null} for none */ public Help getHelp() { return help; } /** * @param help help or {@code null} for none */ public ErrorDetails setHelp(Help help) { this.help = help; return this; } /** * @return value or {@code null} for none */ public LocalizedMessage getLocalizedMessage() { return localizedMessage; } /** * @param localizedMessage localizedMessage or {@code null} for none */ public ErrorDetails setLocalizedMessage(LocalizedMessage localizedMessage) { this.localizedMessage = localizedMessage; return this; } @Override public ErrorDetails set(String fieldName, Object value) { return (ErrorDetails) super.set(fieldName, value); } @Override public ErrorDetails clone() { return (ErrorDetails) super.clone(); } } } } /** * Model definition for OperationWarnings. */ public static final class Warnings extends com.google.api.client.json.GenericJson { /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Data> data; static { // hack to force ProGuard to consider Data 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(Data.class); } /** * [Output Only] A human-readable description of the warning code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @param code code or {@code null} for none */ public Warnings setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @return value or {@code null} for none */ public java.util.List<Data> getData() { return data; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @param data data or {@code null} for none */ public Warnings setData(java.util.List<Data> data) { this.data = data; return this; } /** * [Output Only] A human-readable description of the warning code. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] A human-readable description of the warning code. * @param message message or {@code null} for none */ public Warnings setMessage(java.lang.String message) { this.message = message; return this; } @Override public Warnings set(String fieldName, Object value) { return (Warnings) super.set(fieldName, value); } @Override public Warnings clone() { return (Warnings) super.clone(); } /** * Model definition for OperationWarningsData. */ public static final class Data extends com.google.api.client.json.GenericJson { /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String key; /** * [Output Only] A warning data value corresponding to the key. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String value; /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @return value or {@code null} for none */ public java.lang.String getKey() { return key; } /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @param key key or {@code null} for none */ public Data setKey(java.lang.String key) { this.key = key; return this; } /** * [Output Only] A warning data value corresponding to the key. * @return value or {@code null} for none */ public java.lang.String getValue() { return value; } /** * [Output Only] A warning data value corresponding to the key. * @param value value or {@code null} for none */ public Data setValue(java.lang.String value) { this.value = value; return this; } @Override public Data set(String fieldName, Object value) { return (Data) super.set(fieldName, value); } @Override public Data clone() { return (Data) super.clone(); } } } }
googleapis/google-cloud-java
35,327
java-retail/proto-google-cloud-retail-v2beta/src/main/java/com/google/cloud/retail/v2beta/ListControlsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2beta/control_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.retail.v2beta; /** * * * <pre> * Response for ListControls method. * </pre> * * Protobuf type {@code google.cloud.retail.v2beta.ListControlsResponse} */ public final class ListControlsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.retail.v2beta.ListControlsResponse) ListControlsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListControlsResponse.newBuilder() to construct. private ListControlsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListControlsResponse() { controls_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListControlsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2beta.ControlServiceProto .internal_static_google_cloud_retail_v2beta_ListControlsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2beta.ControlServiceProto .internal_static_google_cloud_retail_v2beta_ListControlsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2beta.ListControlsResponse.class, com.google.cloud.retail.v2beta.ListControlsResponse.Builder.class); } public static final int CONTROLS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.retail.v2beta.Control> controls_; /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.retail.v2beta.Control> getControlsList() { return controls_; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.retail.v2beta.ControlOrBuilder> getControlsOrBuilderList() { return controls_; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ @java.lang.Override public int getControlsCount() { return controls_.size(); } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ @java.lang.Override public com.google.cloud.retail.v2beta.Control getControls(int index) { return controls_.get(index); } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ @java.lang.Override public com.google.cloud.retail.v2beta.ControlOrBuilder getControlsOrBuilder(int index) { return controls_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < controls_.size(); i++) { output.writeMessage(1, controls_.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 < controls_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, controls_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.retail.v2beta.ListControlsResponse)) { return super.equals(obj); } com.google.cloud.retail.v2beta.ListControlsResponse other = (com.google.cloud.retail.v2beta.ListControlsResponse) obj; if (!getControlsList().equals(other.getControlsList())) 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 (getControlsCount() > 0) { hash = (37 * hash) + CONTROLS_FIELD_NUMBER; hash = (53 * hash) + getControlsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2beta.ListControlsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.retail.v2beta.ListControlsResponse 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 ListControls method. * </pre> * * Protobuf type {@code google.cloud.retail.v2beta.ListControlsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.retail.v2beta.ListControlsResponse) com.google.cloud.retail.v2beta.ListControlsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2beta.ControlServiceProto .internal_static_google_cloud_retail_v2beta_ListControlsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2beta.ControlServiceProto .internal_static_google_cloud_retail_v2beta_ListControlsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2beta.ListControlsResponse.class, com.google.cloud.retail.v2beta.ListControlsResponse.Builder.class); } // Construct using com.google.cloud.retail.v2beta.ListControlsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (controlsBuilder_ == null) { controls_ = java.util.Collections.emptyList(); } else { controls_ = null; controlsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.retail.v2beta.ControlServiceProto .internal_static_google_cloud_retail_v2beta_ListControlsResponse_descriptor; } @java.lang.Override public com.google.cloud.retail.v2beta.ListControlsResponse getDefaultInstanceForType() { return com.google.cloud.retail.v2beta.ListControlsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.retail.v2beta.ListControlsResponse build() { com.google.cloud.retail.v2beta.ListControlsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.retail.v2beta.ListControlsResponse buildPartial() { com.google.cloud.retail.v2beta.ListControlsResponse result = new com.google.cloud.retail.v2beta.ListControlsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.retail.v2beta.ListControlsResponse result) { if (controlsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { controls_ = java.util.Collections.unmodifiableList(controls_); bitField0_ = (bitField0_ & ~0x00000001); } result.controls_ = controls_; } else { result.controls_ = controlsBuilder_.build(); } } private void buildPartial0(com.google.cloud.retail.v2beta.ListControlsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.retail.v2beta.ListControlsResponse) { return mergeFrom((com.google.cloud.retail.v2beta.ListControlsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.retail.v2beta.ListControlsResponse other) { if (other == com.google.cloud.retail.v2beta.ListControlsResponse.getDefaultInstance()) return this; if (controlsBuilder_ == null) { if (!other.controls_.isEmpty()) { if (controls_.isEmpty()) { controls_ = other.controls_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureControlsIsMutable(); controls_.addAll(other.controls_); } onChanged(); } } else { if (!other.controls_.isEmpty()) { if (controlsBuilder_.isEmpty()) { controlsBuilder_.dispose(); controlsBuilder_ = null; controls_ = other.controls_; bitField0_ = (bitField0_ & ~0x00000001); controlsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getControlsFieldBuilder() : null; } else { controlsBuilder_.addAllMessages(other.controls_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.retail.v2beta.Control m = input.readMessage( com.google.cloud.retail.v2beta.Control.parser(), extensionRegistry); if (controlsBuilder_ == null) { ensureControlsIsMutable(); controls_.add(m); } else { controlsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.retail.v2beta.Control> controls_ = java.util.Collections.emptyList(); private void ensureControlsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { controls_ = new java.util.ArrayList<com.google.cloud.retail.v2beta.Control>(controls_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.Control, com.google.cloud.retail.v2beta.Control.Builder, com.google.cloud.retail.v2beta.ControlOrBuilder> controlsBuilder_; /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public java.util.List<com.google.cloud.retail.v2beta.Control> getControlsList() { if (controlsBuilder_ == null) { return java.util.Collections.unmodifiableList(controls_); } else { return controlsBuilder_.getMessageList(); } } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public int getControlsCount() { if (controlsBuilder_ == null) { return controls_.size(); } else { return controlsBuilder_.getCount(); } } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public com.google.cloud.retail.v2beta.Control getControls(int index) { if (controlsBuilder_ == null) { return controls_.get(index); } else { return controlsBuilder_.getMessage(index); } } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder setControls(int index, com.google.cloud.retail.v2beta.Control value) { if (controlsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureControlsIsMutable(); controls_.set(index, value); onChanged(); } else { controlsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder setControls( int index, com.google.cloud.retail.v2beta.Control.Builder builderForValue) { if (controlsBuilder_ == null) { ensureControlsIsMutable(); controls_.set(index, builderForValue.build()); onChanged(); } else { controlsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder addControls(com.google.cloud.retail.v2beta.Control value) { if (controlsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureControlsIsMutable(); controls_.add(value); onChanged(); } else { controlsBuilder_.addMessage(value); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder addControls(int index, com.google.cloud.retail.v2beta.Control value) { if (controlsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureControlsIsMutable(); controls_.add(index, value); onChanged(); } else { controlsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder addControls(com.google.cloud.retail.v2beta.Control.Builder builderForValue) { if (controlsBuilder_ == null) { ensureControlsIsMutable(); controls_.add(builderForValue.build()); onChanged(); } else { controlsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder addControls( int index, com.google.cloud.retail.v2beta.Control.Builder builderForValue) { if (controlsBuilder_ == null) { ensureControlsIsMutable(); controls_.add(index, builderForValue.build()); onChanged(); } else { controlsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder addAllControls( java.lang.Iterable<? extends com.google.cloud.retail.v2beta.Control> values) { if (controlsBuilder_ == null) { ensureControlsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, controls_); onChanged(); } else { controlsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder clearControls() { if (controlsBuilder_ == null) { controls_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { controlsBuilder_.clear(); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public Builder removeControls(int index) { if (controlsBuilder_ == null) { ensureControlsIsMutable(); controls_.remove(index); onChanged(); } else { controlsBuilder_.remove(index); } return this; } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public com.google.cloud.retail.v2beta.Control.Builder getControlsBuilder(int index) { return getControlsFieldBuilder().getBuilder(index); } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public com.google.cloud.retail.v2beta.ControlOrBuilder getControlsOrBuilder(int index) { if (controlsBuilder_ == null) { return controls_.get(index); } else { return controlsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public java.util.List<? extends com.google.cloud.retail.v2beta.ControlOrBuilder> getControlsOrBuilderList() { if (controlsBuilder_ != null) { return controlsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(controls_); } } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public com.google.cloud.retail.v2beta.Control.Builder addControlsBuilder() { return getControlsFieldBuilder() .addBuilder(com.google.cloud.retail.v2beta.Control.getDefaultInstance()); } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public com.google.cloud.retail.v2beta.Control.Builder addControlsBuilder(int index) { return getControlsFieldBuilder() .addBuilder(index, com.google.cloud.retail.v2beta.Control.getDefaultInstance()); } /** * * * <pre> * All the Controls for a given catalog. * </pre> * * <code>repeated .google.cloud.retail.v2beta.Control controls = 1;</code> */ public java.util.List<com.google.cloud.retail.v2beta.Control.Builder> getControlsBuilderList() { return getControlsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.Control, com.google.cloud.retail.v2beta.Control.Builder, com.google.cloud.retail.v2beta.ControlOrBuilder> getControlsFieldBuilder() { if (controlsBuilder_ == null) { controlsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.retail.v2beta.Control, com.google.cloud.retail.v2beta.Control.Builder, com.google.cloud.retail.v2beta.ControlOrBuilder>( controls_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); controls_ = null; } return controlsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Pagination token, if not returned indicates the last page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.retail.v2beta.ListControlsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.retail.v2beta.ListControlsResponse) private static final com.google.cloud.retail.v2beta.ListControlsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.retail.v2beta.ListControlsResponse(); } public static com.google.cloud.retail.v2beta.ListControlsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListControlsResponse> PARSER = new com.google.protobuf.AbstractParser<ListControlsResponse>() { @java.lang.Override public ListControlsResponse 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<ListControlsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListControlsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.retail.v2beta.ListControlsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/sdk-platform-java
35,234
java-showcase/proto-gapic-showcase-v1beta1/src/main/java/com/google/showcase/v1beta1/Issue.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: schema/google/showcase/v1beta1/testing.proto // Protobuf Java Version: 3.25.8 package com.google.showcase.v1beta1; /** * * * <pre> * An issue found in the test. * </pre> * * Protobuf type {@code google.showcase.v1beta1.Issue} */ public final class Issue extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.showcase.v1beta1.Issue) IssueOrBuilder { private static final long serialVersionUID = 0L; // Use Issue.newBuilder() to construct. private Issue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Issue() { type_ = 0; severity_ = 0; description_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Issue(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.TestingOuterClass .internal_static_google_showcase_v1beta1_Issue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.TestingOuterClass .internal_static_google_showcase_v1beta1_Issue_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.Issue.class, com.google.showcase.v1beta1.Issue.Builder.class); } /** * * * <pre> * The different potential types of issues. * </pre> * * Protobuf enum {@code google.showcase.v1beta1.Issue.Type} */ public enum Type implements com.google.protobuf.ProtocolMessageEnum { /** <code>TYPE_UNSPECIFIED = 0;</code> */ TYPE_UNSPECIFIED(0), /** * * * <pre> * The test was never instrumented. * </pre> * * <code>SKIPPED = 1;</code> */ SKIPPED(1), /** * * * <pre> * The test was started but never confirmed. * </pre> * * <code>PENDING = 2;</code> */ PENDING(2), /** * * * <pre> * The test was instrumented, but Showcase got an unexpected * value when the generator tried to confirm success. * </pre> * * <code>INCORRECT_CONFIRMATION = 3;</code> */ INCORRECT_CONFIRMATION(3), UNRECOGNIZED(-1), ; /** <code>TYPE_UNSPECIFIED = 0;</code> */ public static final int TYPE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * The test was never instrumented. * </pre> * * <code>SKIPPED = 1;</code> */ public static final int SKIPPED_VALUE = 1; /** * * * <pre> * The test was started but never confirmed. * </pre> * * <code>PENDING = 2;</code> */ public static final int PENDING_VALUE = 2; /** * * * <pre> * The test was instrumented, but Showcase got an unexpected * value when the generator tried to confirm success. * </pre> * * <code>INCORRECT_CONFIRMATION = 3;</code> */ public static final int INCORRECT_CONFIRMATION_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 Type 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 Type forNumber(int value) { switch (value) { case 0: return TYPE_UNSPECIFIED; case 1: return SKIPPED; case 2: return PENDING; case 3: return INCORRECT_CONFIRMATION; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { public Type findValueByNumber(int number) { return Type.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.showcase.v1beta1.Issue.getDescriptor().getEnumTypes().get(0); } private static final Type[] VALUES = values(); public static Type 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 Type(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.showcase.v1beta1.Issue.Type) } /** * * * <pre> * Severity levels. * </pre> * * Protobuf enum {@code google.showcase.v1beta1.Issue.Severity} */ public enum Severity implements com.google.protobuf.ProtocolMessageEnum { /** <code>SEVERITY_UNSPECIFIED = 0;</code> */ SEVERITY_UNSPECIFIED(0), /** * * * <pre> * Errors. * </pre> * * <code>ERROR = 1;</code> */ ERROR(1), /** * * * <pre> * Warnings. * </pre> * * <code>WARNING = 2;</code> */ WARNING(2), UNRECOGNIZED(-1), ; /** <code>SEVERITY_UNSPECIFIED = 0;</code> */ public static final int SEVERITY_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Errors. * </pre> * * <code>ERROR = 1;</code> */ public static final int ERROR_VALUE = 1; /** * * * <pre> * Warnings. * </pre> * * <code>WARNING = 2;</code> */ public static final int WARNING_VALUE = 2; 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 Severity 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 Severity forNumber(int value) { switch (value) { case 0: return SEVERITY_UNSPECIFIED; case 1: return ERROR; case 2: return WARNING; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Severity> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Severity> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Severity>() { public Severity findValueByNumber(int number) { return Severity.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.showcase.v1beta1.Issue.getDescriptor().getEnumTypes().get(1); } private static final Severity[] VALUES = values(); public static Severity 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 Severity(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.showcase.v1beta1.Issue.Severity) } public static final int TYPE_FIELD_NUMBER = 1; private int type_ = 0; /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @return The type. */ @java.lang.Override public com.google.showcase.v1beta1.Issue.Type getType() { com.google.showcase.v1beta1.Issue.Type result = com.google.showcase.v1beta1.Issue.Type.forNumber(type_); return result == null ? com.google.showcase.v1beta1.Issue.Type.UNRECOGNIZED : result; } public static final int SEVERITY_FIELD_NUMBER = 2; private int severity_ = 0; /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @return The enum numeric value on the wire for severity. */ @java.lang.Override public int getSeverityValue() { return severity_; } /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @return The severity. */ @java.lang.Override public com.google.showcase.v1beta1.Issue.Severity getSeverity() { com.google.showcase.v1beta1.Issue.Severity result = com.google.showcase.v1beta1.Issue.Severity.forNumber(severity_); return result == null ? com.google.showcase.v1beta1.Issue.Severity.UNRECOGNIZED : result; } public static final int DESCRIPTION_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object description_ = ""; /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @return The description. */ @java.lang.Override public java.lang.String getDescription() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } } /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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 (type_ != com.google.showcase.v1beta1.Issue.Type.TYPE_UNSPECIFIED.getNumber()) { output.writeEnum(1, type_); } if (severity_ != com.google.showcase.v1beta1.Issue.Severity.SEVERITY_UNSPECIFIED.getNumber()) { output.writeEnum(2, severity_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, description_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (type_ != com.google.showcase.v1beta1.Issue.Type.TYPE_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, type_); } if (severity_ != com.google.showcase.v1beta1.Issue.Severity.SEVERITY_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, severity_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, description_); } 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.showcase.v1beta1.Issue)) { return super.equals(obj); } com.google.showcase.v1beta1.Issue other = (com.google.showcase.v1beta1.Issue) obj; if (type_ != other.type_) return false; if (severity_ != other.severity_) return false; if (!getDescription().equals(other.getDescription())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (37 * hash) + SEVERITY_FIELD_NUMBER; hash = (53 * hash) + severity_; hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getDescription().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.showcase.v1beta1.Issue parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.Issue parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.showcase.v1beta1.Issue parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.Issue 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.showcase.v1beta1.Issue parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.showcase.v1beta1.Issue parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.showcase.v1beta1.Issue parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.Issue 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.showcase.v1beta1.Issue parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.Issue 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.showcase.v1beta1.Issue parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.showcase.v1beta1.Issue 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.showcase.v1beta1.Issue prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * An issue found in the test. * </pre> * * Protobuf type {@code google.showcase.v1beta1.Issue} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.showcase.v1beta1.Issue) com.google.showcase.v1beta1.IssueOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.showcase.v1beta1.TestingOuterClass .internal_static_google_showcase_v1beta1_Issue_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.showcase.v1beta1.TestingOuterClass .internal_static_google_showcase_v1beta1_Issue_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.showcase.v1beta1.Issue.class, com.google.showcase.v1beta1.Issue.Builder.class); } // Construct using com.google.showcase.v1beta1.Issue.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; type_ = 0; severity_ = 0; description_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.showcase.v1beta1.TestingOuterClass .internal_static_google_showcase_v1beta1_Issue_descriptor; } @java.lang.Override public com.google.showcase.v1beta1.Issue getDefaultInstanceForType() { return com.google.showcase.v1beta1.Issue.getDefaultInstance(); } @java.lang.Override public com.google.showcase.v1beta1.Issue build() { com.google.showcase.v1beta1.Issue result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.showcase.v1beta1.Issue buildPartial() { com.google.showcase.v1beta1.Issue result = new com.google.showcase.v1beta1.Issue(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.showcase.v1beta1.Issue result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.type_ = type_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.severity_ = severity_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.description_ = description_; } } @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.showcase.v1beta1.Issue) { return mergeFrom((com.google.showcase.v1beta1.Issue) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.showcase.v1beta1.Issue other) { if (other == com.google.showcase.v1beta1.Issue.getDefaultInstance()) return this; if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } if (other.severity_ != 0) { setSeverityValue(other.getSeverityValue()); } if (!other.getDescription().isEmpty()) { description_ = other.description_; 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 8: { type_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { severity_ = input.readEnum(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { description_ = 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 int type_ = 0; /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @return The enum numeric value on the wire for type. */ @java.lang.Override public int getTypeValue() { return type_; } /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setTypeValue(int value) { type_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @return The type. */ @java.lang.Override public com.google.showcase.v1beta1.Issue.Type getType() { com.google.showcase.v1beta1.Issue.Type result = com.google.showcase.v1beta1.Issue.Type.forNumber(type_); return result == null ? com.google.showcase.v1beta1.Issue.Type.UNRECOGNIZED : result; } /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @param value The type to set. * @return This builder for chaining. */ public Builder setType(com.google.showcase.v1beta1.Issue.Type value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; type_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * The type of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Type type = 1;</code> * * @return This builder for chaining. */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000001); type_ = 0; onChanged(); return this; } private int severity_ = 0; /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @return The enum numeric value on the wire for severity. */ @java.lang.Override public int getSeverityValue() { return severity_; } /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @param value The enum numeric value on the wire for severity to set. * @return This builder for chaining. */ public Builder setSeverityValue(int value) { severity_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @return The severity. */ @java.lang.Override public com.google.showcase.v1beta1.Issue.Severity getSeverity() { com.google.showcase.v1beta1.Issue.Severity result = com.google.showcase.v1beta1.Issue.Severity.forNumber(severity_); return result == null ? com.google.showcase.v1beta1.Issue.Severity.UNRECOGNIZED : result; } /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @param value The severity to set. * @return This builder for chaining. */ public Builder setSeverity(com.google.showcase.v1beta1.Issue.Severity value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; severity_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * The severity of the issue. * </pre> * * <code>.google.showcase.v1beta1.Issue.Severity severity = 2;</code> * * @return This builder for chaining. */ public Builder clearSeverity() { bitField0_ = (bitField0_ & ~0x00000002); severity_ = 0; onChanged(); return this; } private java.lang.Object description_ = ""; /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @return The description. */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @return The bytes for description. */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @param value The description to set. * @return This builder for chaining. */ public Builder setDescription(java.lang.String value) { if (value == null) { throw new NullPointerException(); } description_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @return This builder for chaining. */ public Builder clearDescription() { description_ = getDefaultInstance().getDescription(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A description of the issue. * </pre> * * <code>string description = 3;</code> * * @param value The bytes for description to set. * @return This builder for chaining. */ public Builder setDescriptionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); description_ = value; bitField0_ |= 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.showcase.v1beta1.Issue) } // @@protoc_insertion_point(class_scope:google.showcase.v1beta1.Issue) private static final com.google.showcase.v1beta1.Issue DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.showcase.v1beta1.Issue(); } public static com.google.showcase.v1beta1.Issue getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Issue> PARSER = new com.google.protobuf.AbstractParser<Issue>() { @java.lang.Override public Issue 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<Issue> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Issue> getParserForType() { return PARSER; } @java.lang.Override public com.google.showcase.v1beta1.Issue getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
34,534
java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/AutoMLTranslationProto.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/v3/automl_translation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.translate.v3; public final class AutoMLTranslationProto { private AutoMLTranslationProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ImportDataRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ImportDataRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DatasetInputConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DatasetInputConfig_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DatasetInputConfig_InputFile_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DatasetInputConfig_InputFile_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ImportDataMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ImportDataMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ExportDataRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ExportDataRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DatasetOutputConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DatasetOutputConfig_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ExportDataMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ExportDataMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DeleteDatasetRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DeleteDatasetRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DeleteDatasetMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DeleteDatasetMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_GetDatasetRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_GetDatasetRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListDatasetsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListDatasetsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListDatasetsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListDatasetsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_CreateDatasetRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_CreateDatasetRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_CreateDatasetMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_CreateDatasetMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListExamplesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListExamplesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListExamplesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_Example_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_Example_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_TransferResourceResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_TransferResourceResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_Dataset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_Dataset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_CreateModelRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_CreateModelRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_CreateModelMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_CreateModelMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListModelsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_ListModelsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_ListModelsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_GetModelRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_GetModelRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DeleteModelRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DeleteModelRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_DeleteModelMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_DeleteModelMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_translation_v3_Model_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_translation_v3_Model_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n2google/cloud/translate/v3/automl_trans" + "lation.proto\022\033google.cloud.translation.v" + "3\032\037google/api/field_behavior.proto\032\031goog" + "le/api/resource.proto\032&google/cloud/tran" + "slate/v3/common.proto\032\037google/protobuf/t" + "imestamp.proto\032\027google/rpc/status.proto\"" + "u\n\021ImportDataRequest\022\024\n\007dataset\030\001 \001(\tB\003\340" + "A\002\022J\n\014input_config\030\002 \001(\0132/.google.cloud." + "translation.v3.DatasetInputConfigB\003\340A\002\"\322" + "\001\n\022DatasetInputConfig\022N\n\013input_files\030\001 \003" + "(\01329.google.cloud.translation.v3.Dataset" + "InputConfig.InputFile\032l\n\tInputFile\022\022\n\005us" + "age\030\002 \001(\tB\003\340A\001\022A\n\ngcs_source\030\003 \001(\0132+.goo" + "gle.cloud.translation.v3.GcsInputSourceH" + "\000B\010\n\006source\"\325\001\n\022ImportDataMetadata\022:\n\005st" + "ate\030\001 \001(\0162+.google.cloud.translation.v3." + "OperationState\022/\n\013create_time\030\002 \001(\0132\032.go" + "ogle.protobuf.Timestamp\022/\n\013update_time\030\003" + " \001(\0132\032.google.protobuf.Timestamp\022!\n\005erro" + "r\030\004 \001(\0132\022.google.rpc.Status\"w\n\021ExportDat" + "aRequest\022\024\n\007dataset\030\001 \001(\tB\003\340A\002\022L\n\routput" + "_config\030\002 \001(\01320.google.cloud.translation" + ".v3.DatasetOutputConfigB\003\340A\002\"r\n\023DatasetO" + "utputConfig\022L\n\017gcs_destination\030\001 \001(\01321.g" + "oogle.cloud.translation.v3.GcsOutputDest" + "inationH\000B\r\n\013destination\"\325\001\n\022ExportDataM" + "etadata\022:\n\005state\030\001 \001(\0162+.google.cloud.tr" + "anslation.v3.OperationState\022/\n\013create_ti" + "me\030\002 \001(\0132\032.google.protobuf.Timestamp\022/\n\013" + "update_time\030\003 \001(\0132\032.google.protobuf.Time" + "stamp\022!\n\005error\030\004 \001(\0132\022.google.rpc.Status" + "\"N\n\024DeleteDatasetRequest\0226\n\004name\030\001 \001(\tB(" + "\340A\002\372A\"\n translate.googleapis.com/Dataset" + "\"\330\001\n\025DeleteDatasetMetadata\022:\n\005state\030\001 \001(" + "\0162+.google.cloud.translation.v3.Operatio" + "nState\022/\n\013create_time\030\002 \001(\0132\032.google.pro" + "tobuf.Timestamp\022/\n\013update_time\030\003 \001(\0132\032.g" + "oogle.protobuf.Timestamp\022!\n\005error\030\004 \001(\0132" + "\022.google.rpc.Status\"K\n\021GetDatasetRequest" + "\0226\n\004name\030\001 \001(\tB(\340A\002\372A\"\n translate.google" + "apis.com/Dataset\"\201\001\n\023ListDatasetsRequest" + "\0229\n\006parent\030\001 \001(\tB)\340A\002\372A#\n!locations.goog" + "leapis.com/Location\022\026\n\tpage_size\030\002 \001(\005B\003" + "\340A\001\022\027\n\npage_token\030\003 \001(\tB\003\340A\001\"g\n\024ListData" + "setsResponse\0226\n\010datasets\030\001 \003(\0132$.google." + "cloud.translation.v3.Dataset\022\027\n\017next_pag" + "e_token\030\002 \001(\t\"\215\001\n\024CreateDatasetRequest\0229" + "\n\006parent\030\001 \001(\tB)\340A\002\372A#\n!locations.google" + "apis.com/Location\022:\n\007dataset\030\002 \001(\0132$.goo" + "gle.cloud.translation.v3.DatasetB\003\340A\002\"\330\001" + "\n\025CreateDatasetMetadata\022:\n\005state\030\001 \001(\0162+" + ".google.cloud.translation.v3.OperationSt" + "ate\022/\n\013create_time\030\002 \001(\0132\032.google.protob" + "uf.Timestamp\022/\n\013update_time\030\003 \001(\0132\032.goog" + "le.protobuf.Timestamp\022!\n\005error\030\004 \001(\0132\022.g" + "oogle.rpc.Status\"\225\001\n\023ListExamplesRequest" + "\0228\n\006parent\030\001 \001(\tB(\340A\002\372A\"\n translate.goog" + "leapis.com/Dataset\022\023\n\006filter\030\002 \001(\tB\003\340A\001\022" + "\026\n\tpage_size\030\003 \001(\005B\003\340A\001\022\027\n\npage_token\030\004 " + "\001(\tB\003\340A\001\"g\n\024ListExamplesResponse\0226\n\010exam" + "ples\030\001 \003(\0132$.google.cloud.translation.v3" + ".Example\022\027\n\017next_page_token\030\002 \001(\t\"\320\001\n\007Ex" + "ample\022\021\n\004name\030\001 \001(\tB\003\340A\003\022\023\n\013source_text\030" + "\002 \001(\t\022\023\n\013target_text\030\003 \001(\t\022\022\n\005usage\030\004 \001(" + "\tB\003\340A\003:t\352Aq\n translate.googleapis.com/Ex" + "ample\022Mprojects/{project}/locations/{loc" + "ation}/datasets/{dataset}/examples/{exam" + "ple}\"\350\001\n\036BatchTransferResourcesResponse\022" + "g\n\tresponses\030\001 \003(\0132T.google.cloud.transl" + "ation.v3.BatchTransferResourcesResponse." + "TransferResourceResponse\032]\n\030TransferReso" + "urceResponse\022\016\n\006source\030\001 \001(\t\022\016\n\006target\030\002" + " \001(\t\022!\n\005error\030\003 \001(\0132\022.google.rpc.Status\"" + "\274\003\n\007Dataset\022\014\n\004name\030\001 \001(\t\022\024\n\014display_nam" + "e\030\002 \001(\t\022\034\n\024source_language_code\030\003 \001(\t\022\034\n" + "\024target_language_code\030\004 \001(\t\022\032\n\rexample_c" + "ount\030\005 \001(\005B\003\340A\003\022 \n\023train_example_count\030\006" + " \001(\005B\003\340A\003\022#\n\026validate_example_count\030\007 \001(" + "\005B\003\340A\003\022\037\n\022test_example_count\030\010 \001(\005B\003\340A\003\022" + "4\n\013create_time\030\t \001(\0132\032.google.protobuf.T" + "imestampB\003\340A\003\0224\n\013update_time\030\n \001(\0132\032.goo" + "gle.protobuf.TimestampB\003\340A\003:a\352A^\n transl" + "ate.googleapis.com/Dataset\022:projects/{pr" + "oject}/locations/{location}/datasets/{da" + "taset}\"\207\001\n\022CreateModelRequest\0229\n\006parent\030" + "\001 \001(\tB)\340A\002\372A#\n!locations.googleapis.com/" + "Location\0226\n\005model\030\002 \001(\0132\".google.cloud.t" + "ranslation.v3.ModelB\003\340A\002\"\326\001\n\023CreateModel" + "Metadata\022:\n\005state\030\001 \001(\0162+.google.cloud.t" + "ranslation.v3.OperationState\022/\n\013create_t" + "ime\030\002 \001(\0132\032.google.protobuf.Timestamp\022/\n" + "\013update_time\030\003 \001(\0132\032.google.protobuf.Tim" + "estamp\022!\n\005error\030\004 \001(\0132\022.google.rpc.Statu" + "s\"\224\001\n\021ListModelsRequest\0229\n\006parent\030\001 \001(\tB" + ")\340A\002\372A#\n!locations.googleapis.com/Locati" + "on\022\023\n\006filter\030\004 \001(\tB\003\340A\001\022\026\n\tpage_size\030\002 \001" + "(\005B\003\340A\001\022\027\n\npage_token\030\003 \001(\tB\003\340A\001\"a\n\022List" + "ModelsResponse\0222\n\006models\030\001 \003(\0132\".google." + "cloud.translation.v3.Model\022\027\n\017next_page_" + "token\030\002 \001(\t\"G\n\017GetModelRequest\0224\n\004name\030\001" + " \001(\tB&\340A\002\372A \n\036translate.googleapis.com/M" + "odel\"J\n\022DeleteModelRequest\0224\n\004name\030\001 \001(\t" + "B&\340A\002\372A \n\036translate.googleapis.com/Model" + "\"\326\001\n\023DeleteModelMetadata\022:\n\005state\030\001 \001(\0162" + "+.google.cloud.translation.v3.OperationS" + "tate\022/\n\013create_time\030\002 \001(\0132\032.google.proto" + "buf.Timestamp\022/\n\013update_time\030\003 \001(\0132\032.goo" + "gle.protobuf.Timestamp\022!\n\005error\030\004 \001(\0132\022." + "google.rpc.Status\"\263\003\n\005Model\022\014\n\004name\030\001 \001(" + "\t\022\024\n\014display_name\030\002 \001(\t\022\017\n\007dataset\030\003 \001(\t" + "\022!\n\024source_language_code\030\004 \001(\tB\003\340A\003\022!\n\024t" + "arget_language_code\030\005 \001(\tB\003\340A\003\022 \n\023train_" + "example_count\030\006 \001(\005B\003\340A\003\022#\n\026validate_exa" + "mple_count\030\007 \001(\005B\003\340A\003\022\037\n\022test_example_co" + "unt\030\014 \001(\005B\003\340A\003\0224\n\013create_time\030\010 \001(\0132\032.go" + "ogle.protobuf.TimestampB\003\340A\003\0224\n\013update_t" + "ime\030\n \001(\0132\032.google.protobuf.TimestampB\003\340" + "A\003:[\352AX\n\036translate.googleapis.com/Model\022" + "6projects/{project}/locations/{location}" + "/models/{model}B\315\001\n\035com.google.cloud.tra" + "nslate.v3B\026AutoMLTranslationProtoP\001Z;clo" + "ud.google.com/go/translate/apiv3/transla" + "tepb;translatepb\252\002\031Google.Cloud.Translat" + "e.V3\312\002\031Google\\Cloud\\Translate\\V3\352\002\034Googl" + "e::Cloud::Translate::V3b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.cloud.translate.v3.CommonProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }); internal_static_google_cloud_translation_v3_ImportDataRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_translation_v3_ImportDataRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ImportDataRequest_descriptor, new java.lang.String[] { "Dataset", "InputConfig", }); internal_static_google_cloud_translation_v3_DatasetInputConfig_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_translation_v3_DatasetInputConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DatasetInputConfig_descriptor, new java.lang.String[] { "InputFiles", }); internal_static_google_cloud_translation_v3_DatasetInputConfig_InputFile_descriptor = internal_static_google_cloud_translation_v3_DatasetInputConfig_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_translation_v3_DatasetInputConfig_InputFile_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DatasetInputConfig_InputFile_descriptor, new java.lang.String[] { "Usage", "GcsSource", "Source", }); internal_static_google_cloud_translation_v3_ImportDataMetadata_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_translation_v3_ImportDataMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ImportDataMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_ExportDataRequest_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_translation_v3_ExportDataRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ExportDataRequest_descriptor, new java.lang.String[] { "Dataset", "OutputConfig", }); internal_static_google_cloud_translation_v3_DatasetOutputConfig_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_translation_v3_DatasetOutputConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DatasetOutputConfig_descriptor, new java.lang.String[] { "GcsDestination", "Destination", }); internal_static_google_cloud_translation_v3_ExportDataMetadata_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_translation_v3_ExportDataMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ExportDataMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_DeleteDatasetRequest_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_translation_v3_DeleteDatasetRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DeleteDatasetRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_translation_v3_DeleteDatasetMetadata_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_translation_v3_DeleteDatasetMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DeleteDatasetMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_GetDatasetRequest_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_translation_v3_GetDatasetRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_GetDatasetRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_translation_v3_ListDatasetsRequest_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_translation_v3_ListDatasetsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListDatasetsRequest_descriptor, new java.lang.String[] { "Parent", "PageSize", "PageToken", }); internal_static_google_cloud_translation_v3_ListDatasetsResponse_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_translation_v3_ListDatasetsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListDatasetsResponse_descriptor, new java.lang.String[] { "Datasets", "NextPageToken", }); internal_static_google_cloud_translation_v3_CreateDatasetRequest_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_translation_v3_CreateDatasetRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_CreateDatasetRequest_descriptor, new java.lang.String[] { "Parent", "Dataset", }); internal_static_google_cloud_translation_v3_CreateDatasetMetadata_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_translation_v3_CreateDatasetMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_CreateDatasetMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_ListExamplesRequest_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_translation_v3_ListExamplesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListExamplesRequest_descriptor, new java.lang.String[] { "Parent", "Filter", "PageSize", "PageToken", }); internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_cloud_translation_v3_ListExamplesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor, new java.lang.String[] { "Examples", "NextPageToken", }); internal_static_google_cloud_translation_v3_Example_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_cloud_translation_v3_Example_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_Example_descriptor, new java.lang.String[] { "Name", "SourceText", "TargetText", "Usage", }); internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_descriptor, new java.lang.String[] { "Responses", }); internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_TransferResourceResponse_descriptor = internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_TransferResourceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_BatchTransferResourcesResponse_TransferResourceResponse_descriptor, new java.lang.String[] { "Source", "Target", "Error", }); internal_static_google_cloud_translation_v3_Dataset_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_cloud_translation_v3_Dataset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_Dataset_descriptor, new java.lang.String[] { "Name", "DisplayName", "SourceLanguageCode", "TargetLanguageCode", "ExampleCount", "TrainExampleCount", "ValidateExampleCount", "TestExampleCount", "CreateTime", "UpdateTime", }); internal_static_google_cloud_translation_v3_CreateModelRequest_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_cloud_translation_v3_CreateModelRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_CreateModelRequest_descriptor, new java.lang.String[] { "Parent", "Model", }); internal_static_google_cloud_translation_v3_CreateModelMetadata_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_cloud_translation_v3_CreateModelMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_CreateModelMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_cloud_translation_v3_ListModelsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListModelsRequest_descriptor, new java.lang.String[] { "Parent", "Filter", "PageSize", "PageToken", }); internal_static_google_cloud_translation_v3_ListModelsResponse_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_cloud_translation_v3_ListModelsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_ListModelsResponse_descriptor, new java.lang.String[] { "Models", "NextPageToken", }); internal_static_google_cloud_translation_v3_GetModelRequest_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_google_cloud_translation_v3_GetModelRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_GetModelRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_translation_v3_DeleteModelRequest_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_google_cloud_translation_v3_DeleteModelRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DeleteModelRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_translation_v3_DeleteModelMetadata_descriptor = getDescriptor().getMessageTypes().get(24); internal_static_google_cloud_translation_v3_DeleteModelMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_DeleteModelMetadata_descriptor, new java.lang.String[] { "State", "CreateTime", "UpdateTime", "Error", }); internal_static_google_cloud_translation_v3_Model_descriptor = getDescriptor().getMessageTypes().get(25); internal_static_google_cloud_translation_v3_Model_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_translation_v3_Model_descriptor, new java.lang.String[] { "Name", "DisplayName", "Dataset", "SourceLanguageCode", "TargetLanguageCode", "TrainExampleCount", "ValidateExampleCount", "TestExampleCount", "CreateTime", "UpdateTime", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor( descriptor, registry); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.cloud.translate.v3.CommonProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleapis/google-cloud-java
35,426
java-alloydb/proto-google-cloud-alloydb-v1alpha/src/main/java/com/google/cloud/alloydb/v1alpha/FailoverInstanceRequest.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/v1alpha/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.alloydb.v1alpha; /** * * * <pre> * Message for triggering failover on an Instance * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.FailoverInstanceRequest} */ public final class FailoverInstanceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.alloydb.v1alpha.FailoverInstanceRequest) FailoverInstanceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use FailoverInstanceRequest.newBuilder() to construct. private FailoverInstanceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FailoverInstanceRequest() { name_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FailoverInstanceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_FailoverInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_FailoverInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.class, com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest)) { return super.equals(obj); } com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest other = (com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest) obj; if (!getName().equals(other.getName())) return false; if (!getRequestId().equals(other.getRequestId())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest 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.v1alpha.FailoverInstanceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest 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.v1alpha.FailoverInstanceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest 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.v1alpha.FailoverInstanceRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest 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.v1alpha.FailoverInstanceRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest 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.v1alpha.FailoverInstanceRequest 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 triggering failover on an Instance * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.FailoverInstanceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.alloydb.v1alpha.FailoverInstanceRequest) com.google.cloud.alloydb.v1alpha.FailoverInstanceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_FailoverInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_FailoverInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.class, com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.Builder.class); } // Construct using com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; requestId_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_FailoverInstanceRequest_descriptor; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest getDefaultInstanceForType() { return com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest build() { com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest buildPartial() { com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest result = new com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.requestId_ = requestId_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest) { return mergeFrom((com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest other) { if (other == com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getRequestId().isEmpty()) { requestId_ = other.requestId_; bitField0_ |= 0x00000002; onChanged(); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { requestId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Instance.name field. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private boolean validateOnly_; /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.alloydb.v1alpha.FailoverInstanceRequest) } // @@protoc_insertion_point(class_scope:google.cloud.alloydb.v1alpha.FailoverInstanceRequest) private static final com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest(); } public static com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FailoverInstanceRequest> PARSER = new com.google.protobuf.AbstractParser<FailoverInstanceRequest>() { @java.lang.Override public FailoverInstanceRequest 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<FailoverInstanceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FailoverInstanceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.FailoverInstanceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/reef
35,578
lang/java/reef-bridge-java/src/main/java/org/apache/reef/javabridge/generic/JobDriver.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.reef.javabridge.generic; import org.apache.reef.driver.client.JobMessageObserver; import org.apache.reef.driver.context.ActiveContext; import org.apache.reef.driver.context.ClosedContext; import org.apache.reef.driver.context.ContextMessage; import org.apache.reef.driver.context.FailedContext; import org.apache.reef.driver.evaluator.*; import org.apache.reef.driver.restart.DriverRestarted; import org.apache.reef.driver.task.*; import org.apache.reef.io.network.naming.NameServer; import org.apache.reef.javabridge.*; import org.apache.reef.driver.restart.DriverRestartCompleted; import org.apache.reef.runtime.common.driver.DriverStatusManager; import org.apache.reef.runtime.common.driver.parameters.DefinedRuntimes; import org.apache.reef.runtime.common.files.REEFFileNames; import org.apache.reef.tang.annotations.Parameter; import org.apache.reef.tang.annotations.Unit; import org.apache.reef.util.Optional; import org.apache.reef.util.logging.CLRBufferedLogHandler; import org.apache.reef.util.logging.LoggingScope; import org.apache.reef.util.logging.LoggingScopeFactory; import org.apache.reef.wake.EventHandler; import org.apache.reef.wake.remote.address.LocalAddressProvider; import org.apache.reef.wake.remote.impl.ObjectSerializableCodec; import org.apache.reef.wake.time.Clock; import org.apache.reef.wake.time.event.Alarm; import org.apache.reef.wake.time.event.StartTime; import org.apache.reef.wake.time.event.StopTime; import org.apache.reef.webserver.*; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * Generic job driver for CLRBridge. */ @Unit public final class JobDriver { private static final Logger LOG = Logger.getLogger(JobDriver.class.getName()); /** * String codec is used to encode the results * before passing them back to the client. */ private static final ObjectSerializableCodec<String> JVM_CODEC = new ObjectSerializableCodec<>(); private final InteropLogger interopLogger = new InteropLogger(); private final NameServer nameServer; private final String nameServerInfo; private final HttpServer httpServer; private final ActiveContextBridgeFactory activeContextBridgeFactory; private final AllocatedEvaluatorBridgeFactory allocatedEvaluatorBridgeFactory; /** * Wake clock is used to schedule periodical job check-ups. */ private final Clock clock; /** * Job observer on the client. * We use it to send results from the driver back to the client. */ private final JobMessageObserver jobMessageObserver; /** * Job driver uses EvaluatorRequestor * to request Evaluators that will run the Tasks. */ private final EvaluatorRequestor evaluatorRequestor; /** * Driver status manager to monitor driver status. */ private final DriverStatusManager driverStatusManager; /** * Factory to setup new CLR process configurations. */ private final CLRProcessFactory clrProcessFactory; /** * Shell execution results from each Evaluator. */ private final List<String> results = new ArrayList<>(); /** * Map from context ID to running evaluator context. */ private final ConcurrentHashMap<String, ActiveContext> contexts = new ConcurrentHashMap<>(); private final REEFFileNames reefFileNames; private final LocalAddressProvider localAddressProvider; /** * Logging scope factory that provides LoggingScope. */ private final LoggingScopeFactory loggingScopeFactory; private final Set<String> definedRuntimes; private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); private BridgeHandlerManager handlerManager = null; private boolean isRestarted = false; // We are holding on to following on bridge side. // Need to add references here so that GC does not collect them. private final ConcurrentHashMap<String, AllocatedEvaluatorBridge> allocatedEvaluatorBridges = new ConcurrentHashMap<>(); private EvaluatorRequestorBridge evaluatorRequestorBridge; /** * Job driver constructor. * All parameters are injected from TANG automatically. * * @param clock Wake clock to schedule and check up running jobs. * @param jobMessageObserver is used to send messages back to the client. * @param evaluatorRequestor is used to request Evaluators. * @param activeContextBridgeFactory */ @Inject JobDriver(final Clock clock, final HttpServer httpServer, final NameServer nameServer, final JobMessageObserver jobMessageObserver, final EvaluatorRequestor evaluatorRequestor, final DriverStatusManager driverStatusManager, final LoggingScopeFactory loggingScopeFactory, final LocalAddressProvider localAddressProvider, final ActiveContextBridgeFactory activeContextBridgeFactory, final REEFFileNames reefFileNames, final AllocatedEvaluatorBridgeFactory allocatedEvaluatorBridgeFactory, final CLRProcessFactory clrProcessFactory, @Parameter(DefinedRuntimes.class) final Set<String> definedRuntimes) { this.clock = clock; this.httpServer = httpServer; this.jobMessageObserver = jobMessageObserver; this.evaluatorRequestor = evaluatorRequestor; this.nameServer = nameServer; this.driverStatusManager = driverStatusManager; this.activeContextBridgeFactory = activeContextBridgeFactory; this.allocatedEvaluatorBridgeFactory = allocatedEvaluatorBridgeFactory; this.nameServerInfo = localAddressProvider.getLocalAddress() + ":" + this.nameServer.getPort(); this.loggingScopeFactory = loggingScopeFactory; this.reefFileNames = reefFileNames; this.localAddressProvider = localAddressProvider; this.clrProcessFactory = clrProcessFactory; this.definedRuntimes = definedRuntimes; } private void setupBridge() { // Signal to the clr buffered log handler that the driver has started and that // we can begin logging LOG.log(Level.INFO, "Initializing CLRBufferedLogHandler..."); try (LoggingScope lb = this.loggingScopeFactory.setupBridge()) { final CLRBufferedLogHandler handler = getCLRBufferedLogHandler(); if (handler == null) { LOG.log(Level.WARNING, "CLRBufferedLogHandler could not be initialized"); } else { handler.setDriverInitialized(); LOG.log(Level.INFO, "CLRBufferedLogHandler init complete."); } final String portNumber = httpServer == null ? null : Integer.toString(httpServer.getPort()); if (portNumber != null) { try { final File outputFileName = new File(reefFileNames.getDriverHttpEndpoint()); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFileName), StandardCharsets.UTF_8)); out.write(localAddressProvider.getLocalAddress() + ":" + portNumber + "\n"); out.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } this.evaluatorRequestorBridge = new EvaluatorRequestorBridge(JobDriver.this.evaluatorRequestor, false, loggingScopeFactory, JobDriver.this.definedRuntimes); JobDriver.this.handlerManager = new BridgeHandlerManager(); NativeInterop.clrSystemSetupBridgeHandlerManager(portNumber, JobDriver.this.handlerManager, evaluatorRequestorBridge); try (LoggingScope lp = this.loggingScopeFactory.getNewLoggingScope("setupBridge::clrSystemHttpServerHandlerOnNext")) { final HttpServerEventBridge httpServerEventBridge = new HttpServerEventBridge("SPEC"); NativeInterop.clrSystemHttpServerHandlerOnNext(JobDriver.this.handlerManager.getHttpServerEventHandler(), httpServerEventBridge, this.interopLogger); final String specList = httpServerEventBridge.getUriSpecification(); LOG.log(Level.INFO, "Starting http server, getUriSpecification: {0}", specList); if (specList != null) { final String[] specs = specList.split(":"); for (final String s : specs) { final HttpHandler h = new HttpServerBridgeEventHandler(); h.setUriSpecification(s); this.httpServer.addHttpHandler(h); } } } } LOG.log(Level.INFO, "CLR Bridge setup."); } private CLRBufferedLogHandler getCLRBufferedLogHandler() { for (final Handler handler : Logger.getLogger("").getHandlers()) { if (handler instanceof CLRBufferedLogHandler) { return (CLRBufferedLogHandler) handler; } } return null; } private void submitEvaluator(final AllocatedEvaluator eval, final EvaluatorProcess process) { eval.setProcess(process); LOG.log(Level.FINE, "Allocated Evaluator: {0}, total running running {1}.", new Object[]{eval.getId(), JobDriver.this.contexts.size()}); final long handler = JobDriver.this.handlerManager.getAllocatedEvaluatorHandler(); if (0 == handler) { throw new RuntimeException("Allocated Evaluator Handler not initialized by CLR."); } final AllocatedEvaluatorBridge allocatedEvaluatorBridge = this.allocatedEvaluatorBridgeFactory.getAllocatedEvaluatorBridge(eval, this.nameServerInfo); allocatedEvaluatorBridges.putIfAbsent(allocatedEvaluatorBridge.getId(), allocatedEvaluatorBridge); NativeInterop.clrSystemAllocatedEvaluatorHandlerOnNext( handler, allocatedEvaluatorBridge, this.interopLogger, this.nameServerInfo, eval.getId()); LOG.log(Level.FINE, "End of JobDriver.Allocated Evaluator: {0}, time: {1}", new Object[] {eval.getId(), dateFormat.format(new Date())}); } private void handleFailedEvaluator(final FailedEvaluator eval, final boolean isRestartFailed) { try (LoggingScope ls = loggingScopeFactory.evaluatorFailed(eval.getId())) { LOG.log(Level.SEVERE, "FailedEvaluator", eval); for (final FailedContext failedContext : eval.getFailedContextList()) { final String failedContextId = failedContext.getId(); LOG.log(Level.INFO, "removing context " + failedContextId + " from job driver contexts."); JobDriver.this.contexts.remove(failedContextId); } final String message = "Evaluator " + eval.getId() + " failed with message: " + eval.getEvaluatorException().getMessage(); JobDriver.this.jobMessageObserver.sendMessageToClient(message.getBytes(StandardCharsets.UTF_8)); if (isRestartFailed) { evaluatorFailedHandlerWaitForCLRBridgeSetup( JobDriver.this.handlerManager.getDriverRestartFailedEvaluatorHandler(), eval, isRestartFailed); } else { evaluatorFailedHandlerWaitForCLRBridgeSetup(JobDriver.this.handlerManager.getFailedEvaluatorHandler(), eval, isRestartFailed); } } } private void evaluatorFailedHandlerWaitForCLRBridgeSetup(final long handle, final FailedEvaluator eval, final boolean isRestartFailed) { if (handle == 0) { if (JobDriver.this.handlerManager != null) { final String message = "No CLR FailedEvaluator handler was set, exiting now"; LOG.log(Level.WARNING, message); JobDriver.this.jobMessageObserver.sendMessageToClient(message.getBytes(StandardCharsets.UTF_8)); } else { clock.scheduleAlarm(0, new EventHandler<Alarm>() { @Override public void onNext(final Alarm time) { if (JobDriver.this.handlerManager != null) { handleFailedEvaluatorInCLR(eval, isRestartFailed); } else { LOG.log(Level.INFO, "Waiting for CLR bridge to be set up"); clock.scheduleAlarm(5000, this); } } }); } } else{ handleFailedEvaluatorInCLR(eval, isRestartFailed); } } private void handleFailedEvaluatorInCLR(final FailedEvaluator eval, final boolean isRestartFailed) { final String message = "CLR FailedEvaluator handler set, handling things with CLR handler."; LOG.log(Level.INFO, message); final FailedEvaluatorBridge failedEvaluatorBridge = new FailedEvaluatorBridge(eval, JobDriver.this.evaluatorRequestor, JobDriver.this.isRestarted, loggingScopeFactory, activeContextBridgeFactory, JobDriver.this.definedRuntimes); if (isRestartFailed) { NativeInterop.clrSystemDriverRestartFailedEvaluatorHandlerOnNext( JobDriver.this.handlerManager.getDriverRestartFailedEvaluatorHandler(), failedEvaluatorBridge, JobDriver.this.interopLogger); } else { NativeInterop.clrSystemFailedEvaluatorHandlerOnNext( JobDriver.this.handlerManager.getFailedEvaluatorHandler(), failedEvaluatorBridge, JobDriver.this.interopLogger); } final int additionalRequestedEvaluatorNumber = failedEvaluatorBridge.getNewlyRequestedEvaluatorNumber(); if (additionalRequestedEvaluatorNumber > 0) { LOG.log(Level.INFO, "number of additional evaluators requested after evaluator failure: " + additionalRequestedEvaluatorNumber); } JobDriver.this.jobMessageObserver.sendMessageToClient(message.getBytes(StandardCharsets.UTF_8)); } /** * Submit a Task to a single Evaluator. */ private void submit(final ActiveContext context) { try { LOG.log(Level.INFO, "Send task to context: {0}", new Object[]{context}); if (JobDriver.this.handlerManager.getActiveContextHandler() == 0) { throw new RuntimeException("Active Context Handler not initialized by CLR."); } final ActiveContextBridge activeContextBridge = activeContextBridgeFactory.getActiveContextBridge(context); NativeInterop.clrSystemActiveContextHandlerOnNext(JobDriver.this.handlerManager.getActiveContextHandler(), activeContextBridge, JobDriver.this.interopLogger); } catch (final Exception ex) { LOG.log(Level.SEVERE, "Fail to submit task to active context"); context.close(); throw new RuntimeException(ex); } } /** * Handles AllocatedEvaluator: Submit an empty context. */ public final class AllocatedEvaluatorHandler implements EventHandler<AllocatedEvaluator> { @Override public void onNext(final AllocatedEvaluator allocatedEvaluator) { try (LoggingScope ls = loggingScopeFactory.evaluatorAllocated(allocatedEvaluator.getId())) { LOG.log(Level.INFO, "AllocatedEvaluatorHandler.OnNext"); JobDriver.this.submitEvaluator(allocatedEvaluator, clrProcessFactory.newEvaluatorProcess()); } } } /** * Receive notification that a new Context is available. */ public final class ActiveContextHandler implements EventHandler<ActiveContext> { @Override public void onNext(final ActiveContext context) { try (LoggingScope ls = loggingScopeFactory.activeContextReceived(context.getId())) { LOG.log(Level.INFO, "ActiveContextHandler: Context available: {0}", new Object[]{context.getId()}); JobDriver.this.contexts.put(context.getId(), context); JobDriver.this.submit(context); } } } /** * Receive notification that the Task has completed successfully. */ public final class CompletedTaskHandler implements EventHandler<CompletedTask> { @Override public void onNext(final CompletedTask task) { LOG.log(Level.INFO, "Completed task: {0}", task.getId()); try (LoggingScope ls = loggingScopeFactory.taskCompleted(task.getId())) { // Take the message returned by the task and add it to the running result. String result = "default result"; try { result = new String(task.get(), StandardCharsets.UTF_8); } catch (final Exception e) { LOG.log(Level.WARNING, "failed to decode task outcome"); } LOG.log(Level.INFO, "Return results to the client:\n{0}", result); JobDriver.this.jobMessageObserver.sendMessageToClient(JVM_CODEC.encode(result)); if (JobDriver.this.handlerManager.getCompletedTaskHandler() == 0) { LOG.log(Level.INFO, "No CLR handler bound to handle completed task."); } else { LOG.log(Level.INFO, "CLR CompletedTaskHandler handler set, handling things with CLR handler."); final CompletedTaskBridge completedTaskBridge = new CompletedTaskBridge(task, activeContextBridgeFactory); NativeInterop.clrSystemCompletedTaskHandlerOnNext(JobDriver.this.handlerManager.getCompletedTaskHandler(), completedTaskBridge, JobDriver.this.interopLogger); } } } } /** * Receive notification that the entire Evaluator had failed. */ public final class FailedEvaluatorHandler implements EventHandler<FailedEvaluator> { @Override public void onNext(final FailedEvaluator eval) { JobDriver.this.handleFailedEvaluator(eval, false); allocatedEvaluatorBridges.remove(eval.getId()); } } /** * Receive notification that the entire Evaluator had failed on Driver Restart. */ public final class DriverRestartFailedEvaluatorHandler implements EventHandler<FailedEvaluator> { @Override public void onNext(final FailedEvaluator eval) { JobDriver.this.handleFailedEvaluator(eval, true); } } final class HttpServerBridgeEventHandler implements HttpHandler { private String uriSpecification; /** * returns URI specification for the handler. */ @Override public String getUriSpecification() { return uriSpecification; } public void setUriSpecification(final String s) { uriSpecification = s; } /** * process http request. */ @Override public void onHttpRequest(final ParsedHttpRequest parsedHttpRequest, final HttpServletResponse response) throws IOException, ServletException { LOG.log(Level.INFO, "HttpServerBridgeEventHandler onHttpRequest: {0}", parsedHttpRequest.getRequestUri()); try (LoggingScope ls = loggingScopeFactory.httpRequest(parsedHttpRequest.getRequestUri())) { final AvroHttpSerializer httpSerializer = new AvroHttpSerializer(); final AvroHttpRequest avroHttpRequest = httpSerializer.toAvro(parsedHttpRequest); final String requestString = httpSerializer.toString(avroHttpRequest); final byte[] requestBytes = requestString.getBytes(Charset.forName(AvroHttpSerializer.JSON_CHARSET)); try { final HttpServerEventBridge httpServerEventBridge = new HttpServerEventBridge(requestBytes); NativeInterop.clrSystemHttpServerHandlerOnNext(JobDriver.this.handlerManager.getHttpServerEventHandler(), httpServerEventBridge, JobDriver.this.interopLogger); final String responseBody = new String(httpServerEventBridge.getQueryResponseData(), "UTF-8"); response.getWriter().println(responseBody); LOG.log(Level.INFO, "HttpServerBridgeEventHandler onHttpRequest received response: {0}", responseBody); } catch (final Exception ex) { LOG.log(Level.SEVERE, "Fail to invoke CLR Http Server handler", ex); throw new RuntimeException(ex); } } } } /** * Handle failed task. */ public final class FailedTaskHandler implements EventHandler<FailedTask> { @Override public void onNext(final FailedTask task) throws RuntimeException { LOG.log(Level.SEVERE, "FailedTask received, will be handle in CLR handler, if set."); if (JobDriver.this.handlerManager.getFailedTaskHandler() == 0) { LOG.log(Level.SEVERE, "Failed Task Handler not initialized by CLR, fail for real."); throw new RuntimeException("Failed Task Handler not initialized by CLR."); } try { final FailedTaskBridge failedTaskBridge = new FailedTaskBridge(task, activeContextBridgeFactory); NativeInterop.clrSystemFailedTaskHandlerOnNext(JobDriver.this.handlerManager.getFailedTaskHandler(), failedTaskBridge, JobDriver.this.interopLogger); } catch (final Exception ex) { LOG.log(Level.SEVERE, "Fail to invoke CLR failed task handler"); throw new RuntimeException(ex); } } } /** * Receive notification that the Task is running. */ public final class RunningTaskHandler implements EventHandler<RunningTask> { @Override public void onNext(final RunningTask task) { try (LoggingScope ls = loggingScopeFactory.taskRunning(task.getId())) { if (JobDriver.this.handlerManager.getRunningTaskHandler() == 0) { LOG.log(Level.INFO, "RunningTask event received but no CLR handler was bound. Exiting handler."); } else { LOG.log(Level.INFO, "RunningTask will be handled by CLR handler. Task Id: {0}", task.getId()); try { final RunningTaskBridge runningTaskBridge = new RunningTaskBridge(task, activeContextBridgeFactory); NativeInterop.clrSystemRunningTaskHandlerOnNext(JobDriver.this.handlerManager.getRunningTaskHandler(), runningTaskBridge, JobDriver.this.interopLogger); } catch (final Exception ex) { LOG.log(Level.WARNING, "Fail to invoke CLR running task handler"); throw new RuntimeException(ex); } } } } } /** * Receive notification that the Task is running when driver restarted. */ public final class DriverRestartRunningTaskHandler implements EventHandler<RunningTask> { @Override public void onNext(final RunningTask task) { try (LoggingScope ls = loggingScopeFactory.driverRestartRunningTask(task.getId())) { clock.scheduleAlarm(0, new EventHandler<Alarm>() { @Override public void onNext(final Alarm time) { if (JobDriver.this.handlerManager != null) { if (JobDriver.this.handlerManager.getDriverRestartRunningTaskHandler() != 0) { LOG.log(Level.INFO, "CLR driver restart RunningTask handler implemented, now handle it in CLR."); NativeInterop.clrSystemDriverRestartRunningTaskHandlerOnNext( JobDriver.this.handlerManager.getDriverRestartRunningTaskHandler(), new RunningTaskBridge(task, activeContextBridgeFactory)); } else { LOG.log(Level.WARNING, "No CLR driver restart RunningTask handler implemented, " + "done with DriverRestartRunningTaskHandler."); } } else { LOG.log(Level.INFO, "Waiting for driver to complete restart process " + "before checking out CLR driver restart RunningTaskHandler..."); clock.scheduleAlarm(2000, this); } } }); } } } /** * Receive notification that an context is active on Evaluator when the driver restarted. */ public final class DriverRestartActiveContextHandler implements EventHandler<ActiveContext> { @Override public void onNext(final ActiveContext context) { try (LoggingScope ls = loggingScopeFactory.driverRestartActiveContextReceived(context.getId())) { JobDriver.this.contexts.put(context.getId(), context); LOG.log(Level.INFO, "DriverRestartActiveContextHandler event received: " + context.getId()); clock.scheduleAlarm(0, new EventHandler<Alarm>() { @Override public void onNext(final Alarm time) { if (JobDriver.this.handlerManager != null) { if (JobDriver.this.handlerManager.getDriverRestartActiveContextHandler() != 0) { LOG.log(Level.INFO, "CLR driver restart ActiveContext handler implemented, now handle it in CLR."); NativeInterop.clrSystemDriverRestartActiveContextHandlerOnNext( JobDriver.this.handlerManager.getDriverRestartActiveContextHandler(), activeContextBridgeFactory.getActiveContextBridge(context)); } else { LOG.log(Level.WARNING, "No CLR driver restart ActiveContext handler implemented, " + "done with DriverRestartActiveContextHandler."); } } else { LOG.log(Level.INFO, "Waiting for driver to complete restart process " + "before checking out CLR driver restart DriverRestartActiveContextHandler..."); clock.scheduleAlarm(2000, this); } } }); } } } /** * Job Driver is ready and the clock is set up: request the evaluators. */ public final class StartHandler implements EventHandler<StartTime> { @Override public void onNext(final StartTime startTime) { try (LoggingScope ls = loggingScopeFactory.driverStart(startTime)) { // CLR bridge setup must be done before other event handlers try to access the CLR bridge // thus we grab a lock on this instance synchronized (JobDriver.this) { setupBridge(); LOG.log(Level.INFO, "Finished CLR bridge setup for {0}", startTime); } NativeInterop.callClrSystemOnStartHandler(); LOG.log(Level.INFO, "Driver Started"); } } } /** * Job driver is restarted after previous crash. */ public final class RestartHandler implements EventHandler<DriverRestarted> { @Override public void onNext(final DriverRestarted driverRestarted) { try (LoggingScope ls = loggingScopeFactory.driverRestart(driverRestarted.getStartTime())) { // CLR bridge setup must be done before other event handlers try to access the CLR bridge // thus we lock on this instance synchronized (JobDriver.this) { JobDriver.this.isRestarted = true; setupBridge(); LOG.log(Level.INFO, "Finished CLR bridge setup for {0}", driverRestarted); } NativeInterop.callClrSystemOnRestartHandler(new DriverRestartedBridge(driverRestarted)); LOG.log(Level.INFO, "Driver Restarted"); } } } /** * Receive notification that driver restart has completed. */ public final class DriverRestartCompletedHandler implements EventHandler<DriverRestartCompleted> { @Override public void onNext(final DriverRestartCompleted driverRestartCompleted) { LOG.log(Level.INFO, "Java DriverRestartCompleted event received at time [{0}]. ", driverRestartCompleted.getCompletedTime()); try (LoggingScope ls = loggingScopeFactory.driverRestartCompleted( driverRestartCompleted.getCompletedTime().getTimestamp())) { if (JobDriver.this.handlerManager.getDriverRestartCompletedHandler() != 0) { LOG.log(Level.INFO, "CLR driver restart handler implemented, now handle it in CLR."); NativeInterop.clrSystemDriverRestartCompletedHandlerOnNext( JobDriver.this.handlerManager.getDriverRestartCompletedHandler(), new DriverRestartCompletedBridge(driverRestartCompleted)); } else { LOG.log(Level.WARNING, "No CLR driver restart handler implemented, done with DriverRestartCompletedHandler."); } } } } /** * Shutting down the job driver: close the evaluators. */ final class StopHandler implements EventHandler<StopTime> { @Override public void onNext(final StopTime time) { LOG.log(Level.INFO, " StopTime: {0}", new Object[]{time}); try (LoggingScope ls = loggingScopeFactory.driverStop(time.getTimestamp())) { for (final ActiveContext context : contexts.values()) { context.close(); } } } } /** * Handler for message received from the Task. */ public final class TaskMessageHandler implements EventHandler<TaskMessage> { @Override public void onNext(final TaskMessage taskMessage) { final String msg = new String(taskMessage.get(), StandardCharsets.UTF_8); LOG.log(Level.INFO, "Received TaskMessage: {0} from CLR", msg); //try (LoggingScope ls = loggingScopeFactory.taskMessageReceived(new String(msg))) { if (JobDriver.this.handlerManager.getTaskMessageHandler() != 0) { final TaskMessageBridge taskMessageBridge = new TaskMessageBridge(taskMessage); // if CLR implements the task message handler, handle the bytes in CLR handler NativeInterop.clrSystemTaskMessageHandlerOnNext(JobDriver.this.handlerManager.getTaskMessageHandler(), taskMessage.get(), taskMessageBridge, JobDriver.this.interopLogger); } //} } } /** * Receive notification that the Task has been suspended. */ public final class SuspendedTaskHandler implements EventHandler<SuspendedTask> { @Override public void onNext(final SuspendedTask task) { final String message = "Received notification that task [" + task.getId() + "] has been suspended."; LOG.log(Level.INFO, message); try (LoggingScope ls = loggingScopeFactory.taskSuspended(task.getId())) { if (JobDriver.this.handlerManager.getSuspendedTaskHandler() != 0) { final SuspendedTaskBridge suspendedTaskBridge = new SuspendedTaskBridge(task, activeContextBridgeFactory); // if CLR implements the suspended task handler, handle it in CLR LOG.log(Level.INFO, "Handling the event of suspended task in CLR bridge."); NativeInterop.clrSystemSuspendedTaskHandlerOnNext(JobDriver.this.handlerManager.getSuspendedTaskHandler(), suspendedTaskBridge); } JobDriver.this.jobMessageObserver.sendMessageToClient(JVM_CODEC.encode(message)); } } } /** * Receive notification that the Evaluator has been shut down. */ public final class CompletedEvaluatorHandler implements EventHandler<CompletedEvaluator> { @Override public void onNext(final CompletedEvaluator evaluator) { LOG.log(Level.INFO, " Completed Evaluator {0}", evaluator.getId()); try (LoggingScope ls = loggingScopeFactory.evaluatorCompleted(evaluator.getId())) { if (JobDriver.this.handlerManager.getCompletedEvaluatorHandler() != 0) { final CompletedEvaluatorBridge completedEvaluatorBridge = new CompletedEvaluatorBridge(evaluator); // if CLR implements the completed evaluator handler, handle it in CLR LOG.log(Level.INFO, "Handling the event of completed evaluator in CLR bridge."); NativeInterop.clrSystemCompletedEvaluatorHandlerOnNext( JobDriver.this.handlerManager.getCompletedEvaluatorHandler(), completedEvaluatorBridge); allocatedEvaluatorBridges.remove(completedEvaluatorBridge.getId()); } } } } /** * Receive notification that the Context had completed. * Remove context from the list of active context. */ public final class ClosedContextHandler implements EventHandler<ClosedContext> { @Override public void onNext(final ClosedContext context) { LOG.log(Level.INFO, "Completed Context: {0}", context.getId()); try (LoggingScope ls = loggingScopeFactory.closedContext(context.getId())) { if (JobDriver.this.handlerManager.getClosedContextHandler() != 0) { final ClosedContextBridge closedContextBridge = new ClosedContextBridge(context, activeContextBridgeFactory); // if CLR implements the closed context handler, handle it in CLR LOG.log(Level.INFO, "Handling the event of closed context in CLR bridge."); NativeInterop.clrSystemClosedContextHandlerOnNext(JobDriver.this.handlerManager.getClosedContextHandler(), closedContextBridge); } JobDriver.this.contexts.remove(context.getId()); } } } /** * Receive notification that the Context had failed. * Remove context from the list of active context and notify the client. */ public final class FailedContextHandler implements EventHandler<FailedContext> { @Override public void onNext(final FailedContext context) { LOG.log(Level.SEVERE, "FailedContext", context); try (LoggingScope ls = loggingScopeFactory.evaluatorFailed(context.getId())) { if (JobDriver.this.handlerManager.getFailedContextHandler() != 0) { final FailedContextBridge failedContextBridge = new FailedContextBridge(context, activeContextBridgeFactory); // if CLR implements the failed context handler, handle it in CLR LOG.log(Level.INFO, "Handling the event of failed context in CLR bridge."); NativeInterop.clrSystemFailedContextHandlerOnNext(JobDriver.this.handlerManager.getFailedContextHandler(), failedContextBridge); } JobDriver.this.contexts.remove(context.getId()); final Optional<byte[]> err = context.getData(); if (err.isPresent()) { JobDriver.this.jobMessageObserver.sendMessageToClient(err.get()); } } } } /** * Receive notification that a ContextMessage has been received. */ public final class ContextMessageHandler implements EventHandler<ContextMessage> { @Override public void onNext(final ContextMessage message) { LOG.log(Level.SEVERE, "Received ContextMessage:", message.get()); try (LoggingScope ls = loggingScopeFactory.contextMessageReceived(new String(message.get(), StandardCharsets.UTF_8))) { if (JobDriver.this.handlerManager.getContextMessageHandler() != 0) { final ContextMessageBridge contextMessageBridge = new ContextMessageBridge(message); // if CLR implements the context message handler, handle it in CLR LOG.log(Level.INFO, "Handling the event of context message in CLR bridge."); NativeInterop.clrSystemContextMessageHandlerOnNext(JobDriver.this.handlerManager.getContextMessageHandler(), contextMessageBridge); } } } } /** * Gets the progress of the application from .NET side. */ public final class ProgressProvider implements org.apache.reef.driver.ProgressProvider { @Override public float getProgress() { if (JobDriver.this.handlerManager != null && JobDriver.this.handlerManager.getProgressProvider() != 0) { return NativeInterop.clrSystemProgressProviderGetProgress(JobDriver.this.handlerManager.getProgressProvider()); } return 0f; } } }
oracle/graal
35,233
truffle/src/com.oracle.truffle.api.dsl.test/src/com/oracle/truffle/api/dsl/test/BindExpressionTest.java
/* * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.api.dsl.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import com.oracle.truffle.api.Assumption; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Introspectable; import com.oracle.truffle.api.dsl.Introspection; import com.oracle.truffle.api.dsl.Introspection.SpecializationInfo; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.dsl.UnsupportedSpecializationException; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindBindsCacheNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindCachedNodeTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindFieldNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindFrameInFallbackGuardTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindFrameTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindInLimitNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindMethodNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindMethodTwiceNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindNodeFieldNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindThisMultipleInstancesTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindThisTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedInAssumptionNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedInLimitNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveCachedWithLibraryNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicAndCachedNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindTransitiveDynamicWithLibraryNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.BindVirtualFrameTestNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.DefaultBindingNodeGen; import com.oracle.truffle.api.dsl.test.BindExpressionTestFactory.IntrospectableNodeGen; import com.oracle.truffle.api.frame.Frame; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.UnsupportedMessageException; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.profiles.InlinedBranchProfile; import com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest; @SuppressWarnings({"truffle-inlining", "truffle-neverdefault", "truffle-sharing", "unused"}) public class BindExpressionTest extends AbstractPolyglotTest { static class TestObject { Object storage = new Object(); Assumption assumption = Truffle.getRuntime().createAssumption(); int counter = 0; int bind() { return counter++; } } /* * Test that storage field extraction works. Unfortunately here we cannot check how many times a * field is read. */ @Test public void testBindField() { BindFieldNode node = BindFieldNodeGen.create(); TestObject o = new TestObject(); node.execute(o); assertFails(() -> node.execute(new TestObject()), UnsupportedSpecializationException.class); } abstract static class BindFieldNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "storage == cachedStorage", limit = "1") Object s0(TestObject a0, @Bind("a0.storage") Object storage, @Cached("storage") Object cachedStorage) { assertSame(storage, cachedStorage); assertSame(a0.storage, storage); return a0; } } /* * This test verifies that the extract expression is invoked exactly once. Even though it is * used multiple times. */ @Test public void testBindMethod() { BindMethodNode node = BindMethodNodeGen.create(); TestObject o = new TestObject(); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindMethodNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "counter == 0") Object s0(TestObject a0, @Bind("a0.bind()") int counter, @Cached("counter") int cachedCounter) { assertEquals(0, counter); assertEquals(0, cachedCounter); return a0; } } /* * This test verifies that the expression is invoked once even if used multiple times in the * guard. */ @Test public void testBindMethodTwice() { BindMethodTwiceNode node = BindMethodTwiceNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindMethodTwiceNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "counter == 0 || counter == 1") Object s0(TestObject a0, @Bind("a0.bind()") int counter, @Cached("counter") int cachedCounter) { assertEquals(0, cachedCounter); return a0; } } /* * Tests that if a guard binds a cached expression indirectly through extract it is not actually * executed multiple times. */ @Test public void testBindBindsCache() { BindBindsCacheNode node = BindBindsCacheNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); node.execute(o); } abstract static class BindBindsCacheNode extends Node { abstract Object execute(Object arg0); @ExpectError("The limit expression has no effect.%") // this guard is trivially true but the DSL cannot detect that yet. @Specialization(guards = "counter == cachedCounter", limit = "3") Object s0(TestObject a0, @Cached("0") int cachedCounter, @Bind("cachedCounter") int counter) { assertEquals(0, counter); assertEquals(0, cachedCounter); return a0; } } /* * We need to make sure introspectable does not include bind parameters. */ @Test public void testIntrospectable() { IntrospectableNode node = IntrospectableNodeGen.create(); TestObject o = new TestObject(); node.execute(o); List<SpecializationInfo> infos = Introspection.getSpecializations(node); assertEquals(1, infos.size()); for (SpecializationInfo info : infos) { assertEquals(1, info.getInstances()); List<Object> cachedData = info.getCachedData(0); assertEquals(1, cachedData.size()); assertSame(o.storage, cachedData.iterator().next()); } } @Introspectable abstract static class IntrospectableNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "storage == cachedStorage", limit = "2") Object s0(TestObject a0, @Bind("a0.storage") Object storage, @Cached("storage") Object cachedStorage) { assertSame(storage, cachedStorage); assertSame(a0.storage, storage); return a0; } } /* * This test verifies that an extract expression can be used in a limit expression if it only * binds cached values. */ @Test public void testBindInLimit() { BindInLimitNode node = BindInLimitNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindInLimitNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "counter == cachedCounter", limit = "limit") Object s0(TestObject a0, @Bind("a0.bind()") int counter, @Bind("2") int limit, @Cached("counter") int cachedCounter) { assertEquals(cachedCounter, counter); assertEquals(cachedCounter, cachedCounter); return a0; } } /* * This test verifies that an extract expression can be chained transitively and its dynamic * nature is preserved. */ @Test public void testBindTransitiveDynamic() { BindTransitiveDynamicNode node = BindTransitiveDynamicNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindTransitiveDynamicNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "counter4 == cachedCounter", limit = "2") Object s0(TestObject a0, @Bind("a0.bind()") int counter1, @Bind("counter1") int counter2, @Bind("counter2") int counter3, @Bind("counter3") int counter4, @Cached("counter3") int cachedCounter) { return a0; } } /* * This test verifies that an extract expression can be chained transitively and its dynamic * nature is preserved. */ @Test public void testBindTransitiveDynamicAndCachedNode() { BindTransitiveDynamicAndCachedNode node = BindTransitiveDynamicAndCachedNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindTransitiveDynamicAndCachedNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "counter1 == counter2", limit = "2") Object s0(TestObject a0, @Bind("a0.bind()") int counter1, @Cached("counter1") int cachedCounter, @Bind("cachedCounter") int counter2) { return a0; } } /* * This test verifies that an extract expression can be chained transitively and its dynamic * nature is preserved when used with a library. */ @Test public void testBindTransitiveDynamicWithLibrary() { BindTransitiveDynamicWithLibraryNode node = adoptNode(BindTransitiveDynamicWithLibraryNodeGen.create()).get(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindTransitiveDynamicWithLibraryNode extends Node { abstract Object execute(Object arg0); // this should not trigger a warning @Specialization(guards = "counter2 < 2", limit = "3") Object s0(TestObject a0, @Bind("a0.bind()") int counter1, @Bind("counter1") int counter2, @CachedLibrary("counter2") InteropLibrary lib) { assertTrue(lib.isNumber(counter2)); return a0; } } /* * This test verifies that an extract expression can be chained transitively and its cached * nature is preserved when used with a library. */ @Test public void testBindTransitiveCachedWithLibrary() { BindTransitiveCachedWithLibraryNode node = BindTransitiveCachedWithLibraryNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); } abstract static class BindTransitiveCachedWithLibraryNode extends Node { abstract Object execute(Object arg0); @ExpectError("The limit expression has no effect.%") @Specialization(limit = "3") Object s0(TestObject a0, @Cached("a0.bind()") int cachedCounter, @Bind("cachedCounter") int counter1, @Bind("counter1") int counter2, @CachedLibrary("counter2") InteropLibrary lib) { assertTrue(lib.isNumber(counter2)); return a0; } } @Test public void testBindTransitiveCachedInLimit() { BindTransitiveCachedInLimitNode node = BindTransitiveCachedInLimitNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } abstract static class BindTransitiveCachedInLimitNode extends Node { abstract Object execute(Object arg0); @Specialization(guards = "cachedBind == counter", limit = "extractCachedLimit2") Object s0(TestObject a0, @Bind("a0.bind()") int counter, @Cached("counter") int cachedBind, @Cached("2") int cachedLimit, @Bind("cachedLimit") int extractCachedLimit1, @Bind("extractCachedLimit1") int extractCachedLimit2) { assertEquals(2, cachedLimit); return a0; } } @Test public void testBindTransitiveCachedInAssumption() { BindTransitiveCachedInAssumptionNode node = BindTransitiveCachedInAssumptionNodeGen.create(); TestObject o = new TestObject(); node.execute(o); node.execute(o); o.assumption.invalidate(); assertFails(() -> node.execute(o), UnsupportedSpecializationException.class); } /* * Test use of assumption is allowed for transitive extracted cached values. */ @SuppressWarnings("truffle-assumption") abstract static class BindTransitiveCachedInAssumptionNode extends Node { abstract Object execute(Object arg0); @Specialization(assumptions = "extractAssumption2") Object s0(TestObject a0, @Cached(value = "a0.assumption", neverDefault = true) Assumption assumption, @Bind("assumption") Assumption extractAssumption1, @Bind("extractAssumption1") Assumption extractAssumption2) { return a0; } } @Test public void testBindNodeField() { BindNodeFieldNode node = BindNodeFieldNodeGen.create(2); TestObject o = new TestObject(); assertEquals(2, node.execute(o)); assertEquals(2, node.execute(o)); } @NodeField(name = "field0", type = int.class) abstract static class BindNodeFieldNode extends Node { abstract Object execute(Object arg0); @Specialization int s0(TestObject a0, @Bind("field0") int field) { return field; } } @Test public void testBindThis() { BindThisTest node = BindThisTestNodeGen.create(); node.execute(); } abstract static class BindThisTest extends Node { abstract void execute(); @Specialization void s0(@Bind Node thisNode) { assertSame(this, thisNode); } } abstract static class BindThisParentTest extends Node { abstract void execute(); @Specialization void s0(@Bind("$node.getParent()") Node thisNode) { assertSame(this.getParent(), thisNode); } } @Test public void testBindThisMultipleInstances() { BindThisMultipleInstancesTest node = BindThisMultipleInstancesTestNodeGen.create(); node.execute(42); node.execute(43); node.execute(44); node.execute(45); } abstract static class BindThisMultipleInstancesTest extends Node { abstract void execute(int arg); @Specialization(guards = "arg == cachedArg", limit = "2") void s0(int arg, @Cached("arg") int cachedArg, @Bind Node thisNode) { /* * The specialization does not bind nodes therefore it returns the current node instead * of the specialization class. */ assertSame(this, this); } @SuppressWarnings("truffle-static-method") @Specialization(guards = "arg == cachedArg", limit = "2") void s1(int arg, @Cached("arg") int cachedArg, @Cached InlinedBranchProfile branchProfile, @Bind Node thisNode) { /* * The specialization does not bind nodes therefore it returns the current node instead * of the specialization class. */ branchProfile.enter(thisNode); assertNotSame(this, thisNode); assertSame(thisNode.getParent(), this); } } private static VirtualFrame makeFrame(Object... args) { return Truffle.getRuntime().createVirtualFrame(args, new FrameDescriptor()); } @Test public void testBindFrame() { BindFrameTest node = adoptNode(BindFrameTestNodeGen.create()).get(); assertEquals(42, node.execute(makeFrame(42), false, false)); assertEquals(42, node.execute(makeFrame(42), true, false)); assertEquals(42, node.execute(makeFrame(42), false, true)); } abstract static class BindFrameTest extends Node { abstract Object execute(Frame f, boolean virtual, boolean materialized); @Specialization(guards = {"!virtual", "!materialized"}) Object doFrame(boolean virtual, boolean materialized, @Bind Frame frame) { return frame.getArguments()[0]; } @Specialization(guards = {"virtual", "!materialized"}) Object doVirtualFrame(boolean virtual, boolean materialized, @Bind VirtualFrame frame) { return frame.getArguments()[0]; } @Specialization Object doMaterialized(boolean virtual, boolean materialized, @Bind MaterializedFrame frame) { return frame.getArguments()[0]; } } @Test public void testBindVirtualFrame() { BindVirtualFrameTest node = adoptNode(BindVirtualFrameTestNodeGen.create()).get(); assertEquals(42, node.execute(makeFrame(42), false, false)); assertEquals(42, node.execute(makeFrame(42), true, false)); assertEquals(42, node.execute(makeFrame(42), false, true)); } abstract static class BindVirtualFrameTest extends Node { abstract Object execute(VirtualFrame f, boolean virtual, boolean materialized); @Specialization(guards = {"!virtual", "!materialized"}) Object doFrame(boolean virtual, boolean materialized, @Bind Frame frame) { return frame.getArguments()[0]; } @Specialization(guards = {"virtual", "!materialized"}) Object doVirtualFrame(boolean virtual, boolean materialized, @Bind VirtualFrame frame) { return frame.getArguments()[0]; } @Specialization Object doMaterialized(boolean virtual, boolean materialized, @Bind MaterializedFrame frame) { return frame.getArguments()[0]; } } @Test public void testBindFrameInFallbackGuard() { // Regression test where the frame is needed in the generated fallback guard. BindFrameInFallbackGuardTest node = adoptNode(BindFrameInFallbackGuardTestNodeGen.create()).get(); assertEquals(2, node.execute(makeFrame(42, 123))); assertEquals(0, node.execute(makeFrame())); } abstract static class BindFrameInFallbackGuardTest extends Node { abstract Object execute(VirtualFrame f); @Specialization(guards = {"frame.getArguments().length != 0"}) Object doSpecialization(@Bind Frame frame) { return frame.getArguments().length; } @Fallback Object doFallback() { return 0; } } /** * Using the frame in a cached expression is not encouraged, but it is possible. Check that the * generated code at least compiles. */ abstract static class CacheFrameTest extends Node { abstract Object execute(Frame f); @Specialization(guards = "true") Object doFrame(@Cached("$frame") Frame f) { return null; } @Specialization(guards = "false") Object doVirtualFrame(@Cached("$frame") VirtualFrame f) { return null; } @Specialization Object doMaterializedFrame(@Cached("$frame.materialize()") MaterializedFrame f) { return null; } } abstract static class CacheVirtualFrameTest extends Node { abstract Object execute(VirtualFrame f); @Specialization(guards = "true") Object doFrame(@Cached("$frame") Frame f) { return null; } @Specialization(guards = "false") Object doVirtualFrame(@Cached("$frame") VirtualFrame f) { return null; } @Specialization Object doMaterializedFrame(@Cached("$frame.materialize()") MaterializedFrame f) { return null; } } @Test public void testBindCachedNodeTest() { BindCachedNodeTest node = adoptNode(BindCachedNodeTestNodeGen.create()).get(); TestObject o = new TestObject(); assertEquals("42", node.execute("42")); } abstract static class BoundTestNode extends Node { abstract Object execute(Object arg); @Specialization Object s0(Object arg) { return arg; } } abstract static class BindCachedNodeTest extends Node { static int LIMIT = 0; abstract Object execute(Object arg0); @Specialization(limit = "LIMIT") Object s0(Object arg0, @Cached BoundTestNode testNode, @Bind("testNode.execute(arg0)") Object result, @CachedLibrary("result") InteropLibrary lib) { try { return lib.asString(result); } catch (UnsupportedMessageException e) { throw CompilerDirectives.shouldNotReachHere(); } } } @SuppressWarnings("truffle-assumption") abstract static class ErrorUseInAssumptionsNode extends Node { abstract Object execute(Object arg0); @ExpectError("Assumption expressions must not bind dynamic parameter values.") @Specialization(assumptions = "assumption") Object s0(TestObject a0, @Bind("a0.assumption") Assumption assumption) { return a0; } } abstract static class ErrorUseInLimitNode extends Node { abstract Object execute(Object arg0); @ExpectError("Limit expressions must not bind dynamic parameter values.") @Specialization(guards = "counter == cachedCounter", limit = "counter") Object s0(TestObject a0, @Bind("a0.bind()") int counter, @Cached("counter") int cachedCounter) { assertEquals(1, counter); assertEquals(1, cachedCounter); return a0; } } abstract static class ErrorCyclicUseNode extends Node { abstract Object execute(Object arg0); @Specialization Object s0(TestObject a0, @Bind("a0.bind()") int extract, @ExpectError("The initializer expression of parameter 'counter1' binds uninitialized parameter 'counter2. Reorder the parameters to resolve the problem.")// @Bind("counter2") int counter1, @Bind("counter1") int counter2) { return a0; } } abstract static class ErrorSyntaxNode extends Node { abstract Object execute(Object arg0); @Specialization Object s0(TestObject a0, @ExpectError("Error parsing expression 'asdf32': asdf32 cannot be resolved.")// @Bind("asdf32") int extract) { return a0; } } abstract static class ErrorEmptyNode extends Node { abstract Object execute(Object arg0); @Specialization Object s0(TestObject a0, @ExpectError("Error parsing expression '': line 1:0 mismatched input '<EOF>'%")// @Bind("") int extract) { return a0; } } /* * We don't want that static node constructors are looked up for extract annotations. This * should only work for Cached. */ abstract static class ErrorUseNodeNode extends Node { abstract Object execute(Object arg0); @Specialization Object s0(TestObject a0, @ExpectError("Error parsing expression 'create()': The method create is undefined for the enclosing scope.")// @Bind("create()") BindFieldNode node) { return a0; } } abstract static class ErrorBindThisWithCachedTest extends Node { abstract void execute(); @Specialization void s0(@ExpectError("Cannot use 'this' with @Cached use @Bind instead.") // @Cached("this") Node thisNode) { } } abstract static class WarningRedundantBindingTest1 extends Node { abstract Object execute(); @Specialization Object s0( @ExpectError("Bind expression '$node' is redundant and can be automatically be resolved from the parameter type.%") // @Bind("$node") Node result) { return null; } } abstract static class WarningRedundantBindingTest2 extends Node { abstract Object execute(); @Specialization Object s0( @ExpectError("Bind expression 'INSTANCE' is redundant and can be automatically be resolved from the parameter type.%") // @Bind("INSTANCE") DefaultBindType result) { return result; } } abstract static class WarningRedundantBindingTest3 extends Node { abstract Object execute(Frame frame); @Specialization(guards = "true") Object s0( @ExpectError("Bind expression '$frame' is redundant and can be automatically be resolved from the parameter type.%") // @Bind("$frame") Frame result) { return result; } @Specialization(guards = "false") Object s1( @ExpectError("Bind expression '$frame' is redundant and can be automatically be resolved from the parameter type.%") // @Bind("$frame") VirtualFrame result) { return result; } @Specialization Object s2( @ExpectError("Bind expression '$frame.materialize()' is redundant and can be automatically be resolved from the parameter type.%") // @Bind("$frame.materialize()") MaterializedFrame result) { return result; } } @Test public void testDefaultBinding() { DefaultBindingNode node = adoptNode(DefaultBindingNodeGen.create()).get(); assertSame(DefaultBindType.INSTANCE, node.execute()); } @Bind.DefaultExpression("INSTANCE") static class DefaultBindType { static final DefaultBindTypeSubclass INSTANCE = new DefaultBindTypeSubclass(); } static class NoBindingType { } abstract static class DefaultBindingNode extends Node { abstract Object execute(); @Specialization Object s0(@Bind DefaultBindType result) { return result; } } static class DefaultBindTypeSubclass extends DefaultBindType { } abstract static class DefaultBindingSubclassNode extends Node { abstract Object execute(); @Specialization Object s0(@Bind DefaultBindTypeSubclass result) { return result; } } @Test public void testDefaultBindingSubclass() { DefaultBindingNode node = adoptNode(DefaultBindingNodeGen.create()).get(); assertSame(DefaultBindType.INSTANCE, node.execute()); } abstract static class ErrorNoDefaultBindingTestNode extends Node { abstract Object execute(); @Specialization Object s0( @ExpectError("No expression specified for @Bind annotation and no @DefaultExpression could be resolved from the parameter type.%") // @Bind NoBindingType result) { return result; } } abstract static class BindRootNodeTestNode extends Node { abstract Object execute(); @Specialization Object s0( @ExpectError("Incompatible return type Node. The expression type must be equal to the parameter type RootNode.") // @Bind RootNode result) { return result; } } abstract static class BindNodeTestNode extends Node { abstract Object execute(); @Specialization Object s0(@Bind Node result) { return result; } } abstract static class BindThisWarningTestNode extends Node { abstract Object execute(); @Specialization Object s0( @ExpectError("This expression binds variable 'this' which should no longer be used. Use the '$node' variable instead to resolve this warning.%")// @Bind("this") Node result) { return result; } } abstract static class BindFrameErrorTestNode extends Node { abstract Object execute(); @Specialization(guards = "true") Object s0( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind Frame frame) { return null; } @Specialization(guards = "false") Object s1( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind VirtualFrame frame) { return null; } @Specialization Object s2( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind MaterializedFrame frame) { return null; } } abstract static class BindFrameError2TestNode extends Node { abstract Object execute(Frame frame); abstract Object executeWithoutFrame(); @Specialization(guards = "true") Object s0( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind Frame frame) { return null; } @Specialization(guards = "false") Object s1( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind VirtualFrame frame) { return null; } @Specialization Object s2( @ExpectError("This expression binds the frame, but the frame is not available for this node. Declare a frame parameter on all execute methods to resolve this error.")// @Bind MaterializedFrame frame) { return null; } } }
google/j2objc
35,252
translator/src/main/java/com/google/devtools/j2objc/gen/TypeDeclarationGenerator.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. */ package com.google.devtools.j2objc.gen; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MultimapBuilder; import com.google.devtools.j2objc.ast.AbstractTypeDeclaration; import com.google.devtools.j2objc.ast.Annotation; import com.google.devtools.j2objc.ast.BodyDeclaration; import com.google.devtools.j2objc.ast.EnumConstantDeclaration; import com.google.devtools.j2objc.ast.EnumDeclaration; import com.google.devtools.j2objc.ast.FieldDeclaration; import com.google.devtools.j2objc.ast.FunctionDeclaration; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.Name; import com.google.devtools.j2objc.ast.NativeDeclaration; import com.google.devtools.j2objc.ast.TreeNode; import com.google.devtools.j2objc.ast.VariableDeclarationFragment; import com.google.devtools.j2objc.util.ElementUtil; import com.google.devtools.j2objc.util.NameTable; import com.google.devtools.j2objc.util.TranslationUtil; import com.google.devtools.j2objc.util.TypeUtil; import com.google.devtools.j2objc.util.UnicodeUtils; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; /** * Base class for generating type declarations, either public or private. * * @author Tom Ball, Keith Stanger */ public class TypeDeclarationGenerator extends TypeGenerator { /** Represents Objective-C's audited nullability regions. */ protected enum AuditedRegion { BEGIN("NS_ASSUME_NONNULL_BEGIN"), END("NS_ASSUME_NONNULL_END"); private final String macro; private AuditedRegion(String macro) { this.macro = macro; } public String getMacro() { return macro; } } private static final String DEPRECATED_ATTRIBUTE = "__attribute__((deprecated))"; private final GeneratedSourceMappings generatedSourceMappings; protected TypeDeclarationGenerator(SourceBuilder builder, AbstractTypeDeclaration node) { super(builder, node); generatedSourceMappings = new GeneratedSourceMappings(); } protected TypeDeclarationGenerator( SourceBuilder builder, AbstractTypeDeclaration node, GeneratedSourceMappings generatedSourceMappings) { super(builder, node); this.generatedSourceMappings = generatedSourceMappings; } public static void generate( SourceBuilder builder, AbstractTypeDeclaration node, GeneratedSourceMappings generatedSourceMappings) { new TypeDeclarationGenerator(builder, node, generatedSourceMappings).generate(); } public static void generate(SourceBuilder builder, AbstractTypeDeclaration node) { new TypeDeclarationGenerator(builder, node).generate(); } protected boolean printPrivateDeclarations() { return false; } @Override protected boolean shouldPrintDeclaration(BodyDeclaration decl) { if (decl instanceof MethodDeclaration && !((MethodDeclaration) decl).hasDeclaration()) { return false; } return decl.hasPrivateDeclaration() == printPrivateDeclarations(); } private void generate() { // If the type is private, then generate nothing in the header. The initial // declaration will go in the implementation file instead. if (!typeNode.hasPrivateDeclaration()) { generateInitialDeclaration(); } } protected void generateInitialDeclaration() { if (typeNode.isDeadClass()) { printStaticFieldDeclarations(); return; } printNativeEnum(); printTypeDocumentation(); printNonnullAuditedRegion(AuditedRegion.BEGIN); printInterfaceType(); printImplementedProtocols(); if (!typeElement.getKind().isInterface()) { printInstanceVariables(); } else { newline(); } if (!typeElement.getKind().isInterface()) { printProperties(); printStaticAccessors(); } printInnerDeclarations(); println("\n@end"); if (ElementUtil.isPackageInfo(typeElement)) { printOuterDeclarations(); printNonnullAuditedRegion(AuditedRegion.END); return; } printCompanionClassDeclaration(); printStaticInitFunction(); printEnumConstants(); printFieldSetters(); printStaticFieldDeclarations(); printOuterDeclarations(); printTypeLiteralDeclaration(); printBoxedOperators(); printUnprefixedAlias(); newline(); printNonnullAuditedRegion(AuditedRegion.END); } private void printNativeEnum() { if (!(typeNode instanceof EnumDeclaration)) { return; } List<EnumConstantDeclaration> constants = ((EnumDeclaration) typeNode).getEnumConstants(); String nativeName = nameTable.getNativeEnumName(typeElement); String ordinalName = NameTable.getNativeOrdinalPreprocessorName(typeName); // C doesn't allow empty enum declarations. Java does, so we skip the // C enum declaration and generate the type declaration. if (!constants.isEmpty()) { newline(); printf("typedef NS_ENUM(int32_t, %s) {\n", nativeName); // Print C enum typedef. indent(); int ordinal = 0; for (EnumConstantDeclaration constant : constants) { printIndent(); String nativeConstantName = nameTable.getNativeEnumConstantName(typeElement, constant); if (options.swiftEnums() && !printPrivateDeclarations()) { printf( "%s NS_SWIFT_NAME(%s) = %d,\n", nativeConstantName, nameTable.getNativeEnumSwiftConstantName(constant), ordinal++); } else { printf("%s = %d,\n", nativeConstantName, ordinal++); } } unindent(); print("}"); if (!printPrivateDeclarations()) { String swiftName = nameTable.getSwiftClassNameFromAnnotation(typeElement, true); if (swiftName != null) { printf(" NS_SWIFT_NAME(%s)", swiftName); } } print(";\n"); // For compatibility with JreEnum(), J2OBJC_ENUM_CONSTANT() and similar macros, for each // native renamed enum constant provide an alias if needed. for (EnumConstantDeclaration constant : constants) { String nativeConstantName = nameTable.getNativeEnumConstantName(typeElement, constant); String caseName = nameTable.getVariableBaseName(constant.getVariableElement()); String compatibilityConstantName = UnicodeUtils.format("%s_Enum_%s", typeName, caseName); if (!nativeConstantName.equals(compatibilityConstantName)) { printf("#define %s %s\n", compatibilityConstantName, nativeConstantName); } } print("\n"); // Use different types for transpiled Java ordinals (which expects ordinals to be int32_t) and // native code using the enum (where stricter ordinal types help clang warnings). printf( "#if J2OBJC_IMPORTED_BY_JAVA_IMPLEMENTATION\n" + "#define %s int32_t\n" + "#else\n" + "#define %s %s\n" + "#endif\n\n", ordinalName, ordinalName, nativeName); } else { printf("#define %s int32_t\n", ordinalName); } } private void printTypeDocumentation() { newline(); JavadocGenerator.printDocComment(getBuilder(), typeNode.getJavadoc()); } private String getSuperTypeName() { TypeElement supertype = TranslationUtil.getSuperType(typeNode); if (supertype != null) { return nameTable.getFullName(supertype); } return "NSObject"; } private List<String> getInterfaceNames() { if (ElementUtil.isAnnotationType(typeElement)) { return Lists.newArrayList("JavaLangAnnotationAnnotation"); } List<String> names = Lists.newArrayList(); for (TypeElement intrface : TranslationUtil.getInterfaceTypes(typeNode)) { names.add(nameTable.getFullName(intrface)); } if (ElementUtil.getQualifiedName(typeElement).equals("java.lang.Enum")) { names.remove("NSCopying"); names.add(0, "NSCopying"); } else if (isInterfaceType()) { names.add("JavaObject"); } return names; } protected void printInterfaceGenerics() { if (generateObjectiveCGenerics(typeElement.asType())) { List<String> genericNames = nameTable.getClassObjCGenericTypeNames(typeElement.asType()); if (!genericNames.isEmpty()) { printf("<%s>", String.join(", ", genericNames)); } } } private void printInterfaceType() { if (!typeNode.hasPrivateDeclaration()) { // Swift Names only need to be on public types because private declarations are private printSwiftName(); } if (needsDeprecatedAttribute(typeNode.getAnnotations())) { println(DEPRECATED_ATTRIBUTE); } if (typeElement.getKind().isInterface()) { printf("@protocol %s", typeName); } else { printf("@interface %s", typeName); printInterfaceGenerics(); printf(" : %s", getSuperTypeName()); } } private void printImplementedProtocols() { List<String> interfaces = getInterfaceNames(); if (!interfaces.isEmpty()) { print(" < "); boolean isFirst = true; for (String name : interfaces) { if (!isFirst) { print(", "); } isFirst = false; print(name); } print(" >"); } } private void printSwiftName() { if (printPrivateDeclarations()) { return; } String swiftName = nameTable.getSwiftClassNameFromAnnotation(typeElement, true); if (swiftName != null) { if ((typeNode instanceof EnumDeclaration)) { swiftName = swiftName + "Class"; } printf(" NS_SWIFT_NAME(%s)\n", swiftName); } } protected void printStaticInterfaceMethods() { for (BodyDeclaration declaration : getInnerDeclarations()) { if (declaration.getKind().equals(TreeNode.Kind.METHOD_DECLARATION)) { printMethodDeclaration((MethodDeclaration) declaration, true); } } } /** Prints the list of static variable and/or enum constant accessor methods. */ protected void printStaticAccessors() { if (options.staticAccessorMethods() && !options.classProperties()) { for (VariableDeclarationFragment fragment : getStaticFields()) { VariableElement var = fragment.getVariableElement(); TypeMirror type = var.asType(); String accessorName = nameTable.getStaticAccessorName(var); String objcType = paddedType(nameTable.getObjCTypeDeclaration(type), var).trim(); TypeElement declaringClass = ElementUtil.getDeclaringClass(var); String baseName = nameTable.getVariableBaseName(var); ExecutableElement getter = ElementUtil.findGetterMethod(baseName, type, declaringClass, /* isStatic= */ true); if (getter == null) { printf("\n+ (%s)%s;\n", objcType, accessorName); } ExecutableElement setter = ElementUtil.findSetterMethod(baseName, type, declaringClass, /* isStatic= */ true); if (setter == null && !ElementUtil.isFinal(var)) { printf("\n+ (void)set%s:(%s)value;\n", NameTable.capitalize(accessorName), objcType); } } if (typeNode instanceof EnumDeclaration) { for (EnumConstantDeclaration constant : ((EnumDeclaration) typeNode).getEnumConstants()) { String accessorName = nameTable.getStaticAccessorName(constant.getVariableElement()); String nullabilitySpecifier = ""; TypeElement element = typeNode.getTypeElement(); if (shouldAddNullableAnnotation(element)) { nullabilitySpecifier = " _Nullable"; } else if (options.nullability() && !nullMarked) { // Only add a nonnull annotation if null marked is not enabled as it is implied // when annotated regions are in use. This code block preserves legacy behavior. nullabilitySpecifier = " _Nonnull"; } printf("\n+ (%s *%s)%s;\n", typeName, nullabilitySpecifier, accessorName); } } } } /** Prints the list of instance variables in a type. */ protected void printInstanceVariables() { Iterable<VariableDeclarationFragment> fields = getInstanceFields(); if (Iterables.isEmpty(fields)) { newline(); return; } // Need direct access to fields possibly from inner classes that are // promoted to top level classes, so must make all visible fields public. println(" {"); println(" @public"); indent(); FieldDeclaration lastDeclaration = null; boolean needsAsterisk = false; for (VariableDeclarationFragment fragment : fields) { VariableElement varElement = fragment.getVariableElement(); FieldDeclaration declaration = (FieldDeclaration) fragment.getParent(); if (declaration != lastDeclaration) { if (lastDeclaration != null) { println(";"); } lastDeclaration = declaration; JavadocGenerator.printDocComment(getBuilder(), declaration.getJavadoc()); printIndent(); if (!ElementUtil.isVolatile(varElement)) { if (ElementUtil.isWeakReference(varElement)) { print("WEAK_ "); } } String objcType = getDeclarationType(varElement); needsAsterisk = objcType.endsWith("*"); if (needsAsterisk) { // Strip pointer from type, as it will be added when appending fragment. // This is necessary to create "Foo *one, *two;" declarations. objcType = objcType.substring(0, objcType.length() - 2); } print(objcType); print(' '); } else { print(", "); } if (needsAsterisk) { print('*'); if (shouldAddNullableAnnotation(varElement)) { print("_Nullable "); } } print(nameTable.getVariableShortName(varElement)); } println(";"); unindent(); println("}"); } protected void printProperties() { Iterable<VariableDeclarationFragment> fields = getAllFields(); for (VariableDeclarationFragment fragment : fields) { PropertyGenerator.generate(fragment, options, nameTable, typeUtil, parametersNonnullByDefault) .ifPresent(this::println); } if (options.classProperties() && typeNode instanceof EnumDeclaration) { for (EnumConstantDeclaration constant : ((EnumDeclaration) typeNode).getEnumConstants()) { String accessorName = nameTable.getStaticAccessorName(constant.getVariableElement()); print("\n@property (readonly, class"); if (options.nullability()) { print(", nonnull"); } String swiftName = accessorName; if (options.swiftEnums()) { swiftName = NameTable.camelCaseName(accessorName, false); } printf(") %s *%s NS_SWIFT_NAME(%s);", typeName, accessorName, swiftName); } } } protected void printCompanionClassDeclaration() { if (!typeElement.getKind().isInterface() || !needsCompanionClass() || printPrivateDeclarations() == needsPublicCompanionClass()) { return; } printf("\n@interface %s : NSObject", typeName); if (ElementUtil.isGeneratedAnnotation(typeElement)) { // Print annotation implementation interface. printf(" < %s >", typeName); } printInstanceVariables(); printProperties(); printStaticInterfaceMethods(); printStaticAccessors(); println("\n@end"); } private void printStaticInitFunction() { if (hasInitializeMethod()) { printf("\nJ2OBJC_STATIC_INIT(%s)\n", typeName); } else { printf("\nJ2OBJC_EMPTY_STATIC_INIT(%s)\n", typeName); } } private void printEnumConstants() { if (typeNode instanceof EnumDeclaration) { newline(); println("/*! INTERNAL ONLY - Use enum accessors declared below. */"); // If the generated source is annotated with nonnull nullability regions, // ensure this type is explicitly marked as nonnull. Failing to do so leads // to the following error: `inferring '_Nonnull' for pointer type within array // is deprecated [-Werror,-Wnullability-inferred-on-nested-type]`. String arrayTypeNamePrefix = nullMarked ? "_Nonnull " : ""; String arrayTypeName = arrayTypeNamePrefix + typeName; printf("FOUNDATION_EXPORT %s *%s_values_[];\n", typeName, arrayTypeName); for (EnumConstantDeclaration constant : ((EnumDeclaration) typeNode).getEnumConstants()) { String varName = nameTable.getVariableBaseName(constant.getVariableElement()); newline(); JavadocGenerator.printDocComment(getBuilder(), constant.getJavadoc()); printf("inline %s *%s_get_%s(void);\n", typeName, typeName, varName); printf("J2OBJC_ENUM_CONSTANT(%s, %s)\n", typeName, varName); } } } private static final Predicate<VariableDeclarationFragment> NEEDS_SETTER = new Predicate<VariableDeclarationFragment>() { @Override public boolean apply(VariableDeclarationFragment fragment) { VariableElement var = fragment.getVariableElement(); if (ElementUtil.isRetainedWithField(var)) { assert !ElementUtil.isPublic(var) : "@RetainedWith fields cannot be public."; return false; } return !var.asType().getKind().isPrimitive() && !ElementUtil.isSynthetic(var) && !ElementUtil.isWeakReference(var); } }; protected void printFieldSetters() { Iterable<VariableDeclarationFragment> fields = Iterables.filter(getInstanceFields(), NEEDS_SETTER); if (Iterables.isEmpty(fields)) { return; } newline(); for (VariableDeclarationFragment fragment : fields) { VariableElement var = fragment.getVariableElement(); String typeStr = nameTable.getObjCTypeDeclaration(var.asType()); if (typeStr.contains(",")) { typeStr = "J2OBJC_ARG(" + typeStr + ')'; } String objcTypePadded = paddedType(typeStr, var).trim(); String fieldName = nameTable.getVariableShortName(var); String isVolatile = ElementUtil.isVolatile(var) ? "_VOLATILE" : ""; println( UnicodeUtils.format( "J2OBJC%s_FIELD_SETTER(%s, %s, %s)", isVolatile, typeName, fieldName, objcTypePadded)); } } protected void printStaticFieldDeclarations() { for (VariableDeclarationFragment fragment : getStaticFields()) { if (typeNode.isDeadClass()) { printDeadClassConstant(fragment); } else { printStaticFieldFullDeclaration(fragment); } } } // Overridden in TypePrivateDeclarationGenerator protected void printStaticFieldDeclaration( VariableDeclarationFragment fragment, String baseDeclaration) { println("/*! INTERNAL ONLY - Use accessor function from above. */"); println("FOUNDATION_EXPORT " + baseDeclaration + ";"); } private void printStaticFieldFullDeclaration(VariableDeclarationFragment fragment) { VariableElement var = fragment.getVariableElement(); boolean isVolatile = ElementUtil.isVolatile(var); String objcType = nameTable.getObjCTypeDeclaration(var.asType()); String objcTypePadded = paddedType(objcType, var); String declType = paddedType(getDeclarationType(var), var); String name = nameTable.getVariableShortName(var); boolean isFinal = ElementUtil.isFinal(var); boolean isPrimitive = var.asType().getKind().isPrimitive(); boolean isConstant = ElementUtil.isPrimitiveConstant(var); String qualifiers = isConstant ? "_CONSTANT" : (isPrimitive ? "_PRIMITIVE" : "_OBJ") + (isVolatile ? "_VOLATILE" : "") + (isFinal ? "_FINAL" : ""); newline(); FieldDeclaration decl = (FieldDeclaration) fragment.getParent(); JavadocGenerator.printDocComment(getBuilder(), decl.getJavadoc()); printf("inline %s%s_get_%s(void);\n", objcTypePadded, typeName, name); if (!isFinal) { printf("inline %s%s_set_%s(%svalue);\n", objcTypePadded, typeName, name, objcTypePadded); if (isPrimitive && !isVolatile) { printf("inline %s *%s_getRef_%s(void);\n", objcType, typeName, name); } } if (isConstant) { Object value = var.getConstantValue(); assert value != null; printf("#define %s_%s %s\n", typeName, name, LiteralGenerator.generate(value)); } else { printStaticFieldDeclaration( fragment, UnicodeUtils.format("%s%s_%s", declType, typeName, name)); } printf( "J2OBJC_STATIC_FIELD%s(%s, %s, %s)\n", qualifiers, typeName, name, objcTypePadded.trim()); } // Overridden in TypePrivateDeclarationGenerator protected void printDeadClassConstant(VariableDeclarationFragment fragment) { VariableElement var = fragment.getVariableElement(); Object value = var.getConstantValue(); assert value != null; String declType = paddedType(getDeclarationType(var), var); String name = nameTable.getVariableShortName(var); if (ElementUtil.isPrimitiveConstant(var)) { printf("#define %s_%s %s\n", typeName, name, LiteralGenerator.generate(value)); } else { println( "FOUNDATION_EXPORT " + UnicodeUtils.format("%s%s_%s", declType, typeName, name) + ";"); } } private void printTypeLiteralDeclaration() { if (needsTypeLiteral()) { newline(); printf("J2OBJC_TYPE_LITERAL_HEADER(%s)\n", typeName); } } private void printBoxedOperators() { PrimitiveType primitiveType = env.typeUtil().unboxedType(typeElement.asType()); if (primitiveType == null) { return; } char binaryName = env.typeUtil().getSignatureName(primitiveType).charAt(0); String primitiveName = TypeUtil.getName(primitiveType); String capName = NameTable.capitalize(primitiveName); String primitiveTypeName = NameTable.getPrimitiveObjCType(primitiveType); String valueMethod = primitiveName + "Value"; if (primitiveName.equals("long")) { valueMethod = "longLongValue"; } else if (primitiveName.equals("byte")) { valueMethod = "charValue"; } newline(); printf("BOXED_INC_AND_DEC(%s, %s, %s)\n", capName, valueMethod, typeName); if ("DFIJ".indexOf(binaryName) >= 0) { printf( "BOXED_COMPOUND_ASSIGN_ARITHMETIC(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } if ("IJ".indexOf(binaryName) >= 0) { printf( "BOXED_COMPOUND_ASSIGN_MOD(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } if ("DF".indexOf(binaryName) >= 0) { printf( "BOXED_COMPOUND_ASSIGN_FPMOD(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } if ("IJ".indexOf(binaryName) >= 0) { printf( "BOXED_COMPOUND_ASSIGN_BITWISE(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } if ("I".indexOf(binaryName) >= 0) { printf( "BOXED_SHIFT_ASSIGN_32(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } if ("J".indexOf(binaryName) >= 0) { printf( "BOXED_SHIFT_ASSIGN_64(%s, %s, %s, %s)\n", capName, valueMethod, primitiveTypeName, typeName); } } private void printUnprefixedAlias() { if (ElementUtil.isTopLevel(typeElement)) { String unprefixedName = NameTable.camelCaseQualifiedName(ElementUtil.getQualifiedName(typeElement)); if (!unprefixedName.equals(typeName)) { if (typeElement.getKind().isInterface()) { // Protocols can't be used in typedefs. printf("\n#define %s %s\n", unprefixedName, typeName); } else { printf("\n@compatibility_alias %s %s;\n", unprefixedName, typeName); } } } } private boolean canPrintPseudoProperty(MethodDeclaration m) { if (!m.isPseudoProperty()) { return false; } ExecutableElement methodElement = m.getExecutableElement(); String methodName = nameTable.getMethodSelector(methodElement); String propertyName = NameTable.lowercaseFirst(methodName.replaceFirst("get", "")); TypeElement declaringClass = ElementUtil.getDeclaringClass(methodElement); if (NameTable.isReservedName(propertyName)) { return false; } // Check if there is a existing property with the same name if (ElementUtil.findField(declaringClass, propertyName) != null) { return false; } return true; } private void printPseudoProperty(MethodDeclaration m) { ExecutableElement methodElement = m.getExecutableElement(); String methodName = nameTable.getMethodSelector(methodElement); String propertyName = NameTable.lowercaseFirst(methodName.replaceFirst("get", "")); TypeElement declaringClass = ElementUtil.getDeclaringClass(methodElement); if (NameTable.isReservedName(propertyName)) { return; } // Check if there is a existing property with the same name if (ElementUtil.findField(declaringClass, propertyName) != null) { return; } TypeMirror returnType = m.getReturnTypeMirror(); ExecutableElement setter = ElementUtil.findSetterMethod(propertyName, returnType, declaringClass, false); newline(); printf( "@property (%snonatomic, %s, %s%s) %s %s;", ElementUtil.isStatic(methodElement) ? "class, " : "", "getter=" + methodName, setter != null ? "setter=" + nameTable.getMethodSelector(setter) : "readonly", shouldAddNullableAnnotation(methodElement) ? ", nullable" : "", getReturnType(m, true), // Generics allowed in headers. propertyName); newline(); } /** * Emit method declaration. * * @param m The method. * @param isCompanionClass If true, emit only if m is a static interface method. */ private void printMethodDeclaration(MethodDeclaration m, boolean isCompanionClass) { ExecutableElement methodElement = m.getExecutableElement(); TypeElement typeElement = ElementUtil.getDeclaringClass(methodElement); boolean allowGenerics = !typeUtil.isProtoClass(typeElement.asType()); if (typeElement.getKind().isInterface()) { // isCompanion and isStatic must be both false (i.e. this prints a non-static method decl // in @protocol) or must both be true (i.e. this prints a static method decl in the // companion class' @interface). if (isCompanionClass != ElementUtil.isStatic(methodElement)) { return; } } newline(); JavadocGenerator.printDocComment(getBuilder(), m.getJavadoc()); if (canPrintPseudoProperty(m)) { printPseudoProperty(m); return; } // Method declarations allow generics. String methodSignature = getMethodSignature(m, allowGenerics); // In order to properly map the method name from the entire signature, we must isolate it from // associated type and parameter declarations. The method name is guaranteed to be between the // first closing parenthesis and first colon (for methods with arguments), or the entirety of // the declaration after the first closing parenthesis (for methods with no arguments). int identifierStartIndex = methodSignature.indexOf(')') + 1; int identifierEndIndex = methodSignature.contains(":") ? methodSignature.indexOf(':') : methodSignature.length(); generatedSourceMappings.addMethodMapping( m /* methodDeclaration */, getBuilder().length() + identifierStartIndex /* targetBegin */, identifierEndIndex - identifierStartIndex /* length */); print(methodSignature); String methodName = nameTable.getMethodSelector(methodElement); if (!m.isConstructor() && NameTable.needsObjcMethodFamilyNoneAttribute(methodName)) { // Getting around a clang warning. // clang assumes that methods with names starting with new, alloc or copy // return objects of the same type as the receiving class, regardless of // the actual declared return type. This attribute tells clang to not do // that, please. // See http://clang.llvm.org/docs/AutomaticReferenceCounting.html // Sections 5.1 (Explicit method family control) // and 5.2.2 (Related result types) print(" OBJC_METHOD_FAMILY_NONE"); } if (!printPrivateDeclarations()) { String swiftName = nameTable.getSwiftMethodNameFromAnnotation(m); if (swiftName != null) { print(" NS_SWIFT_NAME(" + swiftName + ")"); } } if (needsDeprecatedAttribute(m.getAnnotations())) { print(" " + DEPRECATED_ATTRIBUTE); } if (m.isUnavailable()) { print(" NS_UNAVAILABLE"); } if (options.addTextSegmentAttribute()) { print(" J2OBJC_TEXT_SEGMENT"); } println(";"); } @Override protected void printMethodDeclaration(MethodDeclaration m) { printMethodDeclaration(m, false); } private boolean needsDeprecatedAttribute(List<Annotation> annotations) { return options.generateDeprecatedDeclarations() && hasDeprecated(annotations); } private boolean hasDeprecated(List<Annotation> annotations) { for (Annotation annotation : annotations) { Name annotationTypeName = annotation.getTypeName(); String expectedTypeName = annotationTypeName.isQualifiedName() ? "java.lang.Deprecated" : "Deprecated"; if (expectedTypeName.equals(annotationTypeName.getFullyQualifiedName())) { return true; } } return false; } @Override protected void printNativeDeclaration(NativeDeclaration declaration) { String code = declaration.getHeaderCode(); if (code != null) { newline(); print(declaration.getHeaderCode()); } } @Override protected void printFunctionDeclaration(FunctionDeclaration function) { print("\nFOUNDATION_EXPORT " + getFunctionSignature(function, true, false)); if (function.returnsRetained()) { print(" NS_RETURNS_RETAINED"); } if (options.addTextSegmentAttribute()) { print(" J2OBJC_TEXT_SEGMENT"); } println(";"); } protected void printNonnullAuditedRegion(AuditedRegion state) { if (nullMarked) { println(state.getMacro()); } } /** * Defines the categories for grouping declarations in the header. The categories will be emitted * in the header in the same order that they are declared here. */ private enum DeclarationCategory { PUBLIC("#pragma mark Public"), PROTECTED("#pragma mark Protected"), PACKAGE_PRIVATE("#pragma mark Package-Private"), PRIVATE("#pragma mark Private"), UNAVAILABLE("// Disallowed inherited constructors, do not use."); private final String header; DeclarationCategory(String header) { this.header = header; } private static DeclarationCategory categorize(BodyDeclaration decl) { if (decl instanceof MethodDeclaration && ((MethodDeclaration) decl).isUnavailable()) { return UNAVAILABLE; } int mods = decl.getModifiers(); if ((mods & Modifier.PUBLIC) > 0) { return PUBLIC; } else if ((mods & Modifier.PROTECTED) > 0) { return PROTECTED; } else if ((mods & Modifier.PRIVATE) > 0) { return PRIVATE; } return PACKAGE_PRIVATE; } } /** Print method declarations with #pragma mark lines documenting their scope. */ @Override protected void printInnerDeclarations() { // Everything is public in interfaces. if (isInterfaceType() || typeNode.hasPrivateDeclaration()) { super.printInnerDeclarations(); return; } ListMultimap<DeclarationCategory, BodyDeclaration> categorizedDecls = MultimapBuilder.hashKeys().arrayListValues().build(); for (BodyDeclaration innerDecl : getInnerDeclarations()) { categorizedDecls.put(DeclarationCategory.categorize(innerDecl), innerDecl); } // Emit the categorized declarations using the declaration order of the category values. for (DeclarationCategory category : DeclarationCategory.values()) { List<BodyDeclaration> declarations = categorizedDecls.get(category); if (declarations.isEmpty()) { continue; } // Extract MethodDeclaration nodes so that they can be sorted. List<MethodDeclaration> methods = Lists.newArrayList(); for (Iterator<BodyDeclaration> iter = declarations.iterator(); iter.hasNext(); ) { BodyDeclaration decl = iter.next(); if (decl instanceof MethodDeclaration) { methods.add((MethodDeclaration) decl); iter.remove(); } } Collections.sort(methods, METHOD_DECL_ORDER); newline(); println(category.header); printDeclarations(methods); printDeclarations(declarations); } } /** * Method comparator, suitable for documentation and code-completion lists. * * <p>Sort ordering: constructors first, then alphabetical by name. If they have the same name, * then compare the first parameter's simple type name, then the second, etc. */ @VisibleForTesting static final Comparator<MethodDeclaration> METHOD_DECL_ORDER = new Comparator<MethodDeclaration>() { @Override public int compare(MethodDeclaration m1, MethodDeclaration m2) { if (m1.isConstructor() && !m2.isConstructor()) { return -1; } if (!m1.isConstructor() && m2.isConstructor()) { return 1; } String m1Name = ElementUtil.getName(m1.getExecutableElement()); String m2Name = ElementUtil.getName(m2.getExecutableElement()); if (!m1Name.equals(m2Name)) { return m1Name.compareToIgnoreCase(m2Name); } int nParams = m1.getParameters().size(); int nOtherParams = m2.getParameters().size(); int max = Math.min(nParams, nOtherParams); for (int i = 0; i < max; i++) { String paramType = TypeUtil.getName(m1.getParameter(i).getType().getTypeMirror()); String otherParamType = TypeUtil.getName(m2.getParameter(i).getType().getTypeMirror()); if (!paramType.equals(otherParamType)) { return paramType.compareToIgnoreCase(otherParamType); } } return nParams - nOtherParams; } }; }
googleapis/google-cloud-java
35,312
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListReasoningEnginesRequest.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/reasoning_engine_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Request message for * [ReasoningEngineService.ListReasoningEngines][google.cloud.aiplatform.v1.ReasoningEngineService.ListReasoningEngines]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListReasoningEnginesRequest} */ public final class ListReasoningEnginesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListReasoningEnginesRequest) ListReasoningEnginesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListReasoningEnginesRequest.newBuilder() to construct. private ListReasoningEnginesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListReasoningEnginesRequest() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListReasoningEnginesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.ReasoningEngineServiceProto .internal_static_google_cloud_aiplatform_v1_ListReasoningEnginesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.ReasoningEngineServiceProto .internal_static_google_cloud_aiplatform_v1_ListReasoningEnginesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.class, com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 3; private int pageSize_ = 0; /** * * * <pre> * Optional. The standard list page size. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_); } if (pageSize_ != 0) { output.writeInt32(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest other = (com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getFilter().equals(other.getFilter())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest 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.ListReasoningEnginesRequest 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 * [ReasoningEngineService.ListReasoningEngines][google.cloud.aiplatform.v1.ReasoningEngineService.ListReasoningEngines]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListReasoningEnginesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListReasoningEnginesRequest) com.google.cloud.aiplatform.v1.ListReasoningEnginesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.ReasoningEngineServiceProto .internal_static_google_cloud_aiplatform_v1_ListReasoningEnginesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.ReasoningEngineServiceProto .internal_static_google_cloud_aiplatform_v1_ListReasoningEnginesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.class, com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; filter_ = ""; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.ReasoningEngineServiceProto .internal_static_google_cloud_aiplatform_v1_ListReasoningEnginesRequest_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest build() { com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest buildPartial() { com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest result = new com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.pageToken_ = pageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest) { return mergeFrom((com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest other) { if (other == com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the Location to list the ReasoningEngines * from. Format: `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. The standard list filter. * More detail in [AIP-160](https://google.aip.dev/160). * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. The standard list page size. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. The standard list page size. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. The standard list page size. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. The standard list page token. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListReasoningEnginesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListReasoningEnginesRequest) private static final com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest(); } public static com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListReasoningEnginesRequest> PARSER = new com.google.protobuf.AbstractParser<ListReasoningEnginesRequest>() { @java.lang.Override public ListReasoningEnginesRequest 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<ListReasoningEnginesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListReasoningEnginesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListReasoningEnginesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,523
java-talent/grpc-google-cloud-talent-v4beta1/src/main/java/com/google/cloud/talent/v4beta1/TenantServiceGrpc.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.talent.v4beta1; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/cloud/talent/v4beta1/tenant_service.proto") @io.grpc.stub.annotations.GrpcGenerated public final class TenantServiceGrpc { private TenantServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "google.cloud.talent.v4beta1.TenantService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getCreateTenantMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateTenant", requestType = com.google.cloud.talent.v4beta1.CreateTenantRequest.class, responseType = com.google.cloud.talent.v4beta1.Tenant.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getCreateTenantMethod() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getCreateTenantMethod; if ((getCreateTenantMethod = TenantServiceGrpc.getCreateTenantMethod) == null) { synchronized (TenantServiceGrpc.class) { if ((getCreateTenantMethod = TenantServiceGrpc.getCreateTenantMethod) == null) { TenantServiceGrpc.getCreateTenantMethod = getCreateTenantMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.CreateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateTenant")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.CreateTenantRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance())) .setSchemaDescriptor( new TenantServiceMethodDescriptorSupplier("CreateTenant")) .build(); } } } return getCreateTenantMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getGetTenantMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetTenant", requestType = com.google.cloud.talent.v4beta1.GetTenantRequest.class, responseType = com.google.cloud.talent.v4beta1.Tenant.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getGetTenantMethod() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getGetTenantMethod; if ((getGetTenantMethod = TenantServiceGrpc.getGetTenantMethod) == null) { synchronized (TenantServiceGrpc.class) { if ((getGetTenantMethod = TenantServiceGrpc.getGetTenantMethod) == null) { TenantServiceGrpc.getGetTenantMethod = getGetTenantMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.GetTenantRequest, com.google.cloud.talent.v4beta1.Tenant> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetTenant")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.GetTenantRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance())) .setSchemaDescriptor(new TenantServiceMethodDescriptorSupplier("GetTenant")) .build(); } } } return getGetTenantMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getUpdateTenantMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateTenant", requestType = com.google.cloud.talent.v4beta1.UpdateTenantRequest.class, responseType = com.google.cloud.talent.v4beta1.Tenant.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getUpdateTenantMethod() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> getUpdateTenantMethod; if ((getUpdateTenantMethod = TenantServiceGrpc.getUpdateTenantMethod) == null) { synchronized (TenantServiceGrpc.class) { if ((getUpdateTenantMethod = TenantServiceGrpc.getUpdateTenantMethod) == null) { TenantServiceGrpc.getUpdateTenantMethod = getUpdateTenantMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.UpdateTenantRequest, com.google.cloud.talent.v4beta1.Tenant> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateTenant")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.UpdateTenantRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance())) .setSchemaDescriptor( new TenantServiceMethodDescriptorSupplier("UpdateTenant")) .build(); } } } return getUpdateTenantMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteTenantRequest, com.google.protobuf.Empty> getDeleteTenantMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DeleteTenant", requestType = com.google.cloud.talent.v4beta1.DeleteTenantRequest.class, responseType = com.google.protobuf.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteTenantRequest, com.google.protobuf.Empty> getDeleteTenantMethod() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteTenantRequest, com.google.protobuf.Empty> getDeleteTenantMethod; if ((getDeleteTenantMethod = TenantServiceGrpc.getDeleteTenantMethod) == null) { synchronized (TenantServiceGrpc.class) { if ((getDeleteTenantMethod = TenantServiceGrpc.getDeleteTenantMethod) == null) { TenantServiceGrpc.getDeleteTenantMethod = getDeleteTenantMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.DeleteTenantRequest, com.google.protobuf.Empty> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteTenant")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.DeleteTenantRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.protobuf.Empty.getDefaultInstance())) .setSchemaDescriptor( new TenantServiceMethodDescriptorSupplier("DeleteTenant")) .build(); } } } return getDeleteTenantMethod; } private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListTenantsRequest, com.google.cloud.talent.v4beta1.ListTenantsResponse> getListTenantsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListTenants", requestType = com.google.cloud.talent.v4beta1.ListTenantsRequest.class, responseType = com.google.cloud.talent.v4beta1.ListTenantsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListTenantsRequest, com.google.cloud.talent.v4beta1.ListTenantsResponse> getListTenantsMethod() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListTenantsRequest, com.google.cloud.talent.v4beta1.ListTenantsResponse> getListTenantsMethod; if ((getListTenantsMethod = TenantServiceGrpc.getListTenantsMethod) == null) { synchronized (TenantServiceGrpc.class) { if ((getListTenantsMethod = TenantServiceGrpc.getListTenantsMethod) == null) { TenantServiceGrpc.getListTenantsMethod = getListTenantsMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.ListTenantsRequest, com.google.cloud.talent.v4beta1.ListTenantsResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListTenants")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.ListTenantsRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.ListTenantsResponse .getDefaultInstance())) .setSchemaDescriptor(new TenantServiceMethodDescriptorSupplier("ListTenants")) .build(); } } } return getListTenantsMethod; } /** Creates a new async stub that supports all call types for the service */ public static TenantServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<TenantServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<TenantServiceStub>() { @java.lang.Override public TenantServiceStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceStub(channel, callOptions); } }; return TenantServiceStub.newStub(factory, channel); } /** Creates a new blocking-style stub that supports all types of calls on the service */ public static TenantServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<TenantServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<TenantServiceBlockingV2Stub>() { @java.lang.Override public TenantServiceBlockingV2Stub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceBlockingV2Stub(channel, callOptions); } }; return TenantServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static TenantServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<TenantServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<TenantServiceBlockingStub>() { @java.lang.Override public TenantServiceBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceBlockingStub(channel, callOptions); } }; return TenantServiceBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static TenantServiceFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<TenantServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<TenantServiceFutureStub>() { @java.lang.Override public TenantServiceFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceFutureStub(channel, callOptions); } }; return TenantServiceFutureStub.newStub(factory, channel); } /** * * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public interface AsyncService { /** * * * <pre> * Creates a new tenant entity. * </pre> */ default void createTenant( com.google.cloud.talent.v4beta1.CreateTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateTenantMethod(), responseObserver); } /** * * * <pre> * Retrieves specified tenant. * </pre> */ default void getTenant( com.google.cloud.talent.v4beta1.GetTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetTenantMethod(), responseObserver); } /** * * * <pre> * Updates specified tenant. * </pre> */ default void updateTenant( com.google.cloud.talent.v4beta1.UpdateTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getUpdateTenantMethod(), responseObserver); } /** * * * <pre> * Deletes specified tenant. * </pre> */ default void deleteTenant( com.google.cloud.talent.v4beta1.DeleteTenantRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getDeleteTenantMethod(), responseObserver); } /** * * * <pre> * Lists all tenants associated with the project. * </pre> */ default void listTenants( com.google.cloud.talent.v4beta1.ListTenantsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListTenantsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getListTenantsMethod(), responseObserver); } } /** * Base class for the server implementation of the service TenantService. * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public abstract static class TenantServiceImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return TenantServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service TenantService. * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public static final class TenantServiceStub extends io.grpc.stub.AbstractAsyncStub<TenantServiceStub> { private TenantServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TenantServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceStub(channel, callOptions); } /** * * * <pre> * Creates a new tenant entity. * </pre> */ public void createTenant( com.google.cloud.talent.v4beta1.CreateTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateTenantMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Retrieves specified tenant. * </pre> */ public void getTenant( com.google.cloud.talent.v4beta1.GetTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetTenantMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Updates specified tenant. * </pre> */ public void updateTenant( com.google.cloud.talent.v4beta1.UpdateTenantRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdateTenantMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Deletes specified tenant. * </pre> */ public void deleteTenant( com.google.cloud.talent.v4beta1.DeleteTenantRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getDeleteTenantMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Lists all tenants associated with the project. * </pre> */ public void listTenants( com.google.cloud.talent.v4beta1.ListTenantsRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListTenantsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListTenantsMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service TenantService. * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public static final class TenantServiceBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub<TenantServiceBlockingV2Stub> { private TenantServiceBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TenantServiceBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceBlockingV2Stub(channel, callOptions); } /** * * * <pre> * Creates a new tenant entity. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant createTenant( com.google.cloud.talent.v4beta1.CreateTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Retrieves specified tenant. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant getTenant( com.google.cloud.talent.v4beta1.GetTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Updates specified tenant. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant updateTenant( com.google.cloud.talent.v4beta1.UpdateTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Deletes specified tenant. * </pre> */ public com.google.protobuf.Empty deleteTenant( com.google.cloud.talent.v4beta1.DeleteTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Lists all tenants associated with the project. * </pre> */ public com.google.cloud.talent.v4beta1.ListTenantsResponse listTenants( com.google.cloud.talent.v4beta1.ListTenantsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListTenantsMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service TenantService. * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public static final class TenantServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<TenantServiceBlockingStub> { private TenantServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TenantServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceBlockingStub(channel, callOptions); } /** * * * <pre> * Creates a new tenant entity. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant createTenant( com.google.cloud.talent.v4beta1.CreateTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Retrieves specified tenant. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant getTenant( com.google.cloud.talent.v4beta1.GetTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Updates specified tenant. * </pre> */ public com.google.cloud.talent.v4beta1.Tenant updateTenant( com.google.cloud.talent.v4beta1.UpdateTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Deletes specified tenant. * </pre> */ public com.google.protobuf.Empty deleteTenant( com.google.cloud.talent.v4beta1.DeleteTenantRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteTenantMethod(), getCallOptions(), request); } /** * * * <pre> * Lists all tenants associated with the project. * </pre> */ public com.google.cloud.talent.v4beta1.ListTenantsResponse listTenants( com.google.cloud.talent.v4beta1.ListTenantsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListTenantsMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service TenantService. * * <pre> * A service that handles tenant management, including CRUD and enumeration. * </pre> */ public static final class TenantServiceFutureStub extends io.grpc.stub.AbstractFutureStub<TenantServiceFutureStub> { private TenantServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected TenantServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new TenantServiceFutureStub(channel, callOptions); } /** * * * <pre> * Creates a new tenant entity. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Tenant> createTenant(com.google.cloud.talent.v4beta1.CreateTenantRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateTenantMethod(), getCallOptions()), request); } /** * * * <pre> * Retrieves specified tenant. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Tenant> getTenant(com.google.cloud.talent.v4beta1.GetTenantRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetTenantMethod(), getCallOptions()), request); } /** * * * <pre> * Updates specified tenant. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Tenant> updateTenant(com.google.cloud.talent.v4beta1.UpdateTenantRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdateTenantMethod(), getCallOptions()), request); } /** * * * <pre> * Deletes specified tenant. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteTenant(com.google.cloud.talent.v4beta1.DeleteTenantRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getDeleteTenantMethod(), getCallOptions()), request); } /** * * * <pre> * Lists all tenants associated with the project. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.ListTenantsResponse> listTenants(com.google.cloud.talent.v4beta1.ListTenantsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListTenantsMethod(), getCallOptions()), request); } } private static final int METHODID_CREATE_TENANT = 0; private static final int METHODID_GET_TENANT = 1; private static final int METHODID_UPDATE_TENANT = 2; private static final int METHODID_DELETE_TENANT = 3; private static final int METHODID_LIST_TENANTS = 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_TENANT: serviceImpl.createTenant( (com.google.cloud.talent.v4beta1.CreateTenantRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant>) responseObserver); break; case METHODID_GET_TENANT: serviceImpl.getTenant( (com.google.cloud.talent.v4beta1.GetTenantRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant>) responseObserver); break; case METHODID_UPDATE_TENANT: serviceImpl.updateTenant( (com.google.cloud.talent.v4beta1.UpdateTenantRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Tenant>) responseObserver); break; case METHODID_DELETE_TENANT: serviceImpl.deleteTenant( (com.google.cloud.talent.v4beta1.DeleteTenantRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; case METHODID_LIST_TENANTS: serviceImpl.listTenants( (com.google.cloud.talent.v4beta1.ListTenantsRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListTenantsResponse>) 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( getCreateTenantMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.CreateTenantRequest, com.google.cloud.talent.v4beta1.Tenant>(service, METHODID_CREATE_TENANT))) .addMethod( getGetTenantMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.GetTenantRequest, com.google.cloud.talent.v4beta1.Tenant>(service, METHODID_GET_TENANT))) .addMethod( getUpdateTenantMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.UpdateTenantRequest, com.google.cloud.talent.v4beta1.Tenant>(service, METHODID_UPDATE_TENANT))) .addMethod( getDeleteTenantMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.DeleteTenantRequest, com.google.protobuf.Empty>( service, METHODID_DELETE_TENANT))) .addMethod( getListTenantsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.ListTenantsRequest, com.google.cloud.talent.v4beta1.ListTenantsResponse>( service, METHODID_LIST_TENANTS))) .build(); } private abstract static class TenantServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { TenantServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.cloud.talent.v4beta1.TenantServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("TenantService"); } } private static final class TenantServiceFileDescriptorSupplier extends TenantServiceBaseDescriptorSupplier { TenantServiceFileDescriptorSupplier() {} } private static final class TenantServiceMethodDescriptorSupplier extends TenantServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; TenantServiceMethodDescriptorSupplier(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 (TenantServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new TenantServiceFileDescriptorSupplier()) .addMethod(getCreateTenantMethod()) .addMethod(getGetTenantMethod()) .addMethod(getUpdateTenantMethod()) .addMethod(getDeleteTenantMethod()) .addMethod(getListTenantsMethod()) .build(); } } } return result; } }
googleapis/google-cloud-java
35,363
java-deploy/proto-google-cloud-deploy-v1/src/main/java/com/google/cloud/deploy/v1/TargetsPresentCondition.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/deploy/v1/cloud_deploy.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.deploy.v1; /** * * * <pre> * `TargetsPresentCondition` contains information on any Targets referenced in * the Delivery Pipeline that do not actually exist. * </pre> * * Protobuf type {@code google.cloud.deploy.v1.TargetsPresentCondition} */ public final class TargetsPresentCondition extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.deploy.v1.TargetsPresentCondition) TargetsPresentConditionOrBuilder { private static final long serialVersionUID = 0L; // Use TargetsPresentCondition.newBuilder() to construct. private TargetsPresentCondition(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TargetsPresentCondition() { missingTargets_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new TargetsPresentCondition(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_TargetsPresentCondition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_TargetsPresentCondition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.deploy.v1.TargetsPresentCondition.class, com.google.cloud.deploy.v1.TargetsPresentCondition.Builder.class); } private int bitField0_; public static final int STATUS_FIELD_NUMBER = 1; private boolean status_ = false; /** * * * <pre> * True if there aren't any missing Targets. * </pre> * * <code>bool status = 1;</code> * * @return The status. */ @java.lang.Override public boolean getStatus() { return status_; } public static final int MISSING_TARGETS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList missingTargets_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @return A list containing the missingTargets. */ public com.google.protobuf.ProtocolStringList getMissingTargetsList() { return missingTargets_; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The count of missingTargets. */ public int getMissingTargetsCount() { return missingTargets_.size(); } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the element to return. * @return The missingTargets at the given index. */ public java.lang.String getMissingTargets(int index) { return missingTargets_.get(index); } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the value to return. * @return The bytes of the missingTargets at the given index. */ public com.google.protobuf.ByteString getMissingTargetsBytes(int index) { return missingTargets_.getByteString(index); } public static final int UPDATE_TIME_FIELD_NUMBER = 4; private com.google.protobuf.Timestamp updateTime_; /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> * * @return Whether the updateTime field is set. */ @java.lang.Override public boolean hasUpdateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> * * @return The updateTime. */ @java.lang.Override public com.google.protobuf.Timestamp getUpdateTime() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (status_ != false) { output.writeBool(1, status_); } for (int i = 0; i < missingTargets_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, missingTargets_.getRaw(i)); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(4, getUpdateTime()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (status_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, status_); } { int dataSize = 0; for (int i = 0; i < missingTargets_.size(); i++) { dataSize += computeStringSizeNoTag(missingTargets_.getRaw(i)); } size += dataSize; size += 1 * getMissingTargetsList().size(); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getUpdateTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.deploy.v1.TargetsPresentCondition)) { return super.equals(obj); } com.google.cloud.deploy.v1.TargetsPresentCondition other = (com.google.cloud.deploy.v1.TargetsPresentCondition) obj; if (getStatus() != other.getStatus()) return false; if (!getMissingTargetsList().equals(other.getMissingTargetsList())) return false; if (hasUpdateTime() != other.hasUpdateTime()) return false; if (hasUpdateTime()) { if (!getUpdateTime().equals(other.getUpdateTime())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getStatus()); if (getMissingTargetsCount() > 0) { hash = (37 * hash) + MISSING_TARGETS_FIELD_NUMBER; hash = (53 * hash) + getMissingTargetsList().hashCode(); } if (hasUpdateTime()) { hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getUpdateTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.deploy.v1.TargetsPresentCondition parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.deploy.v1.TargetsPresentCondition 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> * `TargetsPresentCondition` contains information on any Targets referenced in * the Delivery Pipeline that do not actually exist. * </pre> * * Protobuf type {@code google.cloud.deploy.v1.TargetsPresentCondition} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.deploy.v1.TargetsPresentCondition) com.google.cloud.deploy.v1.TargetsPresentConditionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_TargetsPresentCondition_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_TargetsPresentCondition_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.deploy.v1.TargetsPresentCondition.class, com.google.cloud.deploy.v1.TargetsPresentCondition.Builder.class); } // Construct using com.google.cloud.deploy.v1.TargetsPresentCondition.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; status_ = false; missingTargets_ = com.google.protobuf.LazyStringArrayList.emptyList(); updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_TargetsPresentCondition_descriptor; } @java.lang.Override public com.google.cloud.deploy.v1.TargetsPresentCondition getDefaultInstanceForType() { return com.google.cloud.deploy.v1.TargetsPresentCondition.getDefaultInstance(); } @java.lang.Override public com.google.cloud.deploy.v1.TargetsPresentCondition build() { com.google.cloud.deploy.v1.TargetsPresentCondition result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.deploy.v1.TargetsPresentCondition buildPartial() { com.google.cloud.deploy.v1.TargetsPresentCondition result = new com.google.cloud.deploy.v1.TargetsPresentCondition(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.deploy.v1.TargetsPresentCondition result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.status_ = status_; } if (((from_bitField0_ & 0x00000002) != 0)) { missingTargets_.makeImmutable(); result.missingTargets_ = missingTargets_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.deploy.v1.TargetsPresentCondition) { return mergeFrom((com.google.cloud.deploy.v1.TargetsPresentCondition) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.deploy.v1.TargetsPresentCondition other) { if (other == com.google.cloud.deploy.v1.TargetsPresentCondition.getDefaultInstance()) return this; if (other.getStatus() != false) { setStatus(other.getStatus()); } if (!other.missingTargets_.isEmpty()) { if (missingTargets_.isEmpty()) { missingTargets_ = other.missingTargets_; bitField0_ |= 0x00000002; } else { ensureMissingTargetsIsMutable(); missingTargets_.addAll(other.missingTargets_); } onChanged(); } if (other.hasUpdateTime()) { mergeUpdateTime(other.getUpdateTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { status_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureMissingTargetsIsMutable(); missingTargets_.add(s); break; } // case 18 case 34: { input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private boolean status_; /** * * * <pre> * True if there aren't any missing Targets. * </pre> * * <code>bool status = 1;</code> * * @return The status. */ @java.lang.Override public boolean getStatus() { return status_; } /** * * * <pre> * True if there aren't any missing Targets. * </pre> * * <code>bool status = 1;</code> * * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(boolean value) { status_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * True if there aren't any missing Targets. * </pre> * * <code>bool status = 1;</code> * * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000001); status_ = false; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList missingTargets_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureMissingTargetsIsMutable() { if (!missingTargets_.isModifiable()) { missingTargets_ = new com.google.protobuf.LazyStringArrayList(missingTargets_); } bitField0_ |= 0x00000002; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @return A list containing the missingTargets. */ public com.google.protobuf.ProtocolStringList getMissingTargetsList() { missingTargets_.makeImmutable(); return missingTargets_; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The count of missingTargets. */ public int getMissingTargetsCount() { return missingTargets_.size(); } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the element to return. * @return The missingTargets at the given index. */ public java.lang.String getMissingTargets(int index) { return missingTargets_.get(index); } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the value to return. * @return The bytes of the missingTargets at the given index. */ public com.google.protobuf.ByteString getMissingTargetsBytes(int index) { return missingTargets_.getByteString(index); } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index to set the value at. * @param value The missingTargets to set. * @return This builder for chaining. */ public Builder setMissingTargets(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureMissingTargetsIsMutable(); missingTargets_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The missingTargets to add. * @return This builder for chaining. */ public Builder addMissingTargets(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureMissingTargetsIsMutable(); missingTargets_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param values The missingTargets to add. * @return This builder for chaining. */ public Builder addAllMissingTargets(java.lang.Iterable<java.lang.String> values) { ensureMissingTargetsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, missingTargets_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearMissingTargets() { missingTargets_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * The list of Target names that do not exist. For example, * `projects/{project_id}/locations/{location_name}/targets/{target_name}`. * </pre> * * <code>repeated string missing_targets = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes of the missingTargets to add. * @return This builder for chaining. */ public Builder addMissingTargetsBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureMissingTargetsIsMutable(); missingTargets_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.protobuf.Timestamp updateTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> updateTimeBuilder_; /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> * * @return Whether the updateTime field is set. */ public boolean hasUpdateTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> * * @return The updateTime. */ public com.google.protobuf.Timestamp getUpdateTime() { if (updateTimeBuilder_ == null) { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } else { return updateTimeBuilder_.getMessage(); } } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateTime_ = value; } else { updateTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (updateTimeBuilder_ == null) { updateTime_ = builderForValue.build(); } else { updateTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && updateTime_ != null && updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getUpdateTimeBuilder().mergeFrom(value); } else { updateTime_ = value; } } else { updateTimeBuilder_.mergeFrom(value); } if (updateTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public Builder clearUpdateTime() { bitField0_ = (bitField0_ & ~0x00000004); updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getUpdateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { if (updateTimeBuilder_ != null) { return updateTimeBuilder_.getMessageOrBuilder(); } else { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } } /** * * * <pre> * Last time the condition was updated. * </pre> * * <code>.google.protobuf.Timestamp update_time = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getUpdateTimeFieldBuilder() { if (updateTimeBuilder_ == null) { updateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getUpdateTime(), getParentForChildren(), isClean()); updateTime_ = null; } return updateTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.deploy.v1.TargetsPresentCondition) } // @@protoc_insertion_point(class_scope:google.cloud.deploy.v1.TargetsPresentCondition) private static final com.google.cloud.deploy.v1.TargetsPresentCondition DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.deploy.v1.TargetsPresentCondition(); } public static com.google.cloud.deploy.v1.TargetsPresentCondition getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TargetsPresentCondition> PARSER = new com.google.protobuf.AbstractParser<TargetsPresentCondition>() { @java.lang.Override public TargetsPresentCondition 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<TargetsPresentCondition> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TargetsPresentCondition> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.deploy.v1.TargetsPresentCondition getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,445
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ExactMatchResults.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> * Results for exact match metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ExactMatchResults} */ public final class ExactMatchResults extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ExactMatchResults) ExactMatchResultsOrBuilder { private static final long serialVersionUID = 0L; // Use ExactMatchResults.newBuilder() to construct. private ExactMatchResults(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExactMatchResults() { exactMatchMetricValues_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExactMatchResults(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ExactMatchResults_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ExactMatchResults_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ExactMatchResults.class, com.google.cloud.aiplatform.v1beta1.ExactMatchResults.Builder.class); } public static final int EXACT_MATCH_METRIC_VALUES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue> exactMatchMetricValues_; /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue> getExactMatchMetricValuesList() { return exactMatchMetricValues_; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder> getExactMatchMetricValuesOrBuilderList() { return exactMatchMetricValues_; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public int getExactMatchMetricValuesCount() { return exactMatchMetricValues_.size(); } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue getExactMatchMetricValues( int index) { return exactMatchMetricValues_.get(index); } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder getExactMatchMetricValuesOrBuilder(int index) { return exactMatchMetricValues_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < exactMatchMetricValues_.size(); i++) { output.writeMessage(1, exactMatchMetricValues_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < exactMatchMetricValues_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, exactMatchMetricValues_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ExactMatchResults)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ExactMatchResults other = (com.google.cloud.aiplatform.v1beta1.ExactMatchResults) obj; if (!getExactMatchMetricValuesList().equals(other.getExactMatchMetricValuesList())) 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 (getExactMatchMetricValuesCount() > 0) { hash = (37 * hash) + EXACT_MATCH_METRIC_VALUES_FIELD_NUMBER; hash = (53 * hash) + getExactMatchMetricValuesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults 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.ExactMatchResults parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults 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.ExactMatchResults parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults 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.ExactMatchResults parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults 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.ExactMatchResults parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults 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.ExactMatchResults 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.ExactMatchResults 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.ExactMatchResults 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> * Results for exact match metric. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ExactMatchResults} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ExactMatchResults) com.google.cloud.aiplatform.v1beta1.ExactMatchResultsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ExactMatchResults_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ExactMatchResults_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ExactMatchResults.class, com.google.cloud.aiplatform.v1beta1.ExactMatchResults.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ExactMatchResults.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (exactMatchMetricValuesBuilder_ == null) { exactMatchMetricValues_ = java.util.Collections.emptyList(); } else { exactMatchMetricValues_ = null; exactMatchMetricValuesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); 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_ExactMatchResults_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchResults getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ExactMatchResults.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchResults build() { com.google.cloud.aiplatform.v1beta1.ExactMatchResults result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchResults buildPartial() { com.google.cloud.aiplatform.v1beta1.ExactMatchResults result = new com.google.cloud.aiplatform.v1beta1.ExactMatchResults(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.ExactMatchResults result) { if (exactMatchMetricValuesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { exactMatchMetricValues_ = java.util.Collections.unmodifiableList(exactMatchMetricValues_); bitField0_ = (bitField0_ & ~0x00000001); } result.exactMatchMetricValues_ = exactMatchMetricValues_; } else { result.exactMatchMetricValues_ = exactMatchMetricValuesBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ExactMatchResults result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.ExactMatchResults) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ExactMatchResults) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ExactMatchResults other) { if (other == com.google.cloud.aiplatform.v1beta1.ExactMatchResults.getDefaultInstance()) return this; if (exactMatchMetricValuesBuilder_ == null) { if (!other.exactMatchMetricValues_.isEmpty()) { if (exactMatchMetricValues_.isEmpty()) { exactMatchMetricValues_ = other.exactMatchMetricValues_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.addAll(other.exactMatchMetricValues_); } onChanged(); } } else { if (!other.exactMatchMetricValues_.isEmpty()) { if (exactMatchMetricValuesBuilder_.isEmpty()) { exactMatchMetricValuesBuilder_.dispose(); exactMatchMetricValuesBuilder_ = null; exactMatchMetricValues_ = other.exactMatchMetricValues_; bitField0_ = (bitField0_ & ~0x00000001); exactMatchMetricValuesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getExactMatchMetricValuesFieldBuilder() : null; } else { exactMatchMetricValuesBuilder_.addAllMessages(other.exactMatchMetricValues_); } } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue m = input.readMessage( com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.parser(), extensionRegistry); if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.add(m); } else { exactMatchMetricValuesBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue> exactMatchMetricValues_ = java.util.Collections.emptyList(); private void ensureExactMatchMetricValuesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { exactMatchMetricValues_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue>( exactMatchMetricValues_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder> exactMatchMetricValuesBuilder_; /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue> getExactMatchMetricValuesList() { if (exactMatchMetricValuesBuilder_ == null) { return java.util.Collections.unmodifiableList(exactMatchMetricValues_); } else { return exactMatchMetricValuesBuilder_.getMessageList(); } } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public int getExactMatchMetricValuesCount() { if (exactMatchMetricValuesBuilder_ == null) { return exactMatchMetricValues_.size(); } else { return exactMatchMetricValuesBuilder_.getCount(); } } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue getExactMatchMetricValues( int index) { if (exactMatchMetricValuesBuilder_ == null) { return exactMatchMetricValues_.get(index); } else { return exactMatchMetricValuesBuilder_.getMessage(index); } } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setExactMatchMetricValues( int index, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue value) { if (exactMatchMetricValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.set(index, value); onChanged(); } else { exactMatchMetricValuesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setExactMatchMetricValues( int index, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder builderForValue) { if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.set(index, builderForValue.build()); onChanged(); } else { exactMatchMetricValuesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder addExactMatchMetricValues( com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue value) { if (exactMatchMetricValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.add(value); onChanged(); } else { exactMatchMetricValuesBuilder_.addMessage(value); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder addExactMatchMetricValues( int index, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue value) { if (exactMatchMetricValuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.add(index, value); onChanged(); } else { exactMatchMetricValuesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder addExactMatchMetricValues( com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder builderForValue) { if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.add(builderForValue.build()); onChanged(); } else { exactMatchMetricValuesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder addExactMatchMetricValues( int index, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder builderForValue) { if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.add(index, builderForValue.build()); onChanged(); } else { exactMatchMetricValuesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder addAllExactMatchMetricValues( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue> values) { if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, exactMatchMetricValues_); onChanged(); } else { exactMatchMetricValuesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearExactMatchMetricValues() { if (exactMatchMetricValuesBuilder_ == null) { exactMatchMetricValues_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { exactMatchMetricValuesBuilder_.clear(); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder removeExactMatchMetricValues(int index) { if (exactMatchMetricValuesBuilder_ == null) { ensureExactMatchMetricValuesIsMutable(); exactMatchMetricValues_.remove(index); onChanged(); } else { exactMatchMetricValuesBuilder_.remove(index); } return this; } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder getExactMatchMetricValuesBuilder(int index) { return getExactMatchMetricValuesFieldBuilder().getBuilder(index); } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder getExactMatchMetricValuesOrBuilder(int index) { if (exactMatchMetricValuesBuilder_ == null) { return exactMatchMetricValues_.get(index); } else { return exactMatchMetricValuesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder> getExactMatchMetricValuesOrBuilderList() { if (exactMatchMetricValuesBuilder_ != null) { return exactMatchMetricValuesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(exactMatchMetricValues_); } } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder addExactMatchMetricValuesBuilder() { return getExactMatchMetricValuesFieldBuilder() .addBuilder( com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.getDefaultInstance()); } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder addExactMatchMetricValuesBuilder(int index) { return getExactMatchMetricValuesFieldBuilder() .addBuilder( index, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.getDefaultInstance()); } /** * * * <pre> * Output only. Exact match metric values. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.ExactMatchMetricValue exact_match_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder> getExactMatchMetricValuesBuilderList() { return getExactMatchMetricValuesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder> getExactMatchMetricValuesFieldBuilder() { if (exactMatchMetricValuesBuilder_ == null) { exactMatchMetricValuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValue.Builder, com.google.cloud.aiplatform.v1beta1.ExactMatchMetricValueOrBuilder>( exactMatchMetricValues_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); exactMatchMetricValues_ = null; } return exactMatchMetricValuesBuilder_; } @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.ExactMatchResults) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ExactMatchResults) private static final com.google.cloud.aiplatform.v1beta1.ExactMatchResults DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ExactMatchResults(); } public static com.google.cloud.aiplatform.v1beta1.ExactMatchResults getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExactMatchResults> PARSER = new com.google.protobuf.AbstractParser<ExactMatchResults>() { @java.lang.Override public ExactMatchResults 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<ExactMatchResults> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExactMatchResults> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ExactMatchResults getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,430
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/OutputAudioConfig.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/audio_config.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * Instructs the speech synthesizer how to generate the output audio content. * If this audio config is supplied in a request, it overrides all existing * text-to-speech settings applied to the agent. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.OutputAudioConfig} */ public final class OutputAudioConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.OutputAudioConfig) OutputAudioConfigOrBuilder { private static final long serialVersionUID = 0L; // Use OutputAudioConfig.newBuilder() to construct. private OutputAudioConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private OutputAudioConfig() { audioEncoding_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new OutputAudioConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.AudioConfigProto .internal_static_google_cloud_dialogflow_v2beta1_OutputAudioConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.AudioConfigProto .internal_static_google_cloud_dialogflow_v2beta1_OutputAudioConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.class, com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.Builder.class); } private int bitField0_; public static final int AUDIO_ENCODING_FIELD_NUMBER = 1; private int audioEncoding_ = 0; /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for audioEncoding. */ @java.lang.Override public int getAudioEncodingValue() { return audioEncoding_; } /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The audioEncoding. */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding getAudioEncoding() { com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding result = com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.forNumber(audioEncoding_); return result == null ? com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.UNRECOGNIZED : result; } public static final int SAMPLE_RATE_HERTZ_FIELD_NUMBER = 2; private int sampleRateHertz_ = 0; /** * * * <pre> * The synthesis sample rate (in hertz) for this audio. If not * provided, then the synthesizer will use the default sample rate based on * the audio encoding. If this is different from the voice's natural sample * rate, then the synthesizer will honor this request by converting to the * desired sample rate (which might result in worse audio quality). * </pre> * * <code>int32 sample_rate_hertz = 2;</code> * * @return The sampleRateHertz. */ @java.lang.Override public int getSampleRateHertz() { return sampleRateHertz_; } public static final int SYNTHESIZE_SPEECH_CONFIG_FIELD_NUMBER = 3; private com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesizeSpeechConfig_; /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> * * @return Whether the synthesizeSpeechConfig field is set. */ @java.lang.Override public boolean hasSynthesizeSpeechConfig() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> * * @return The synthesizeSpeechConfig. */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig getSynthesizeSpeechConfig() { return synthesizeSpeechConfig_ == null ? com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.getDefaultInstance() : synthesizeSpeechConfig_; } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfigOrBuilder getSynthesizeSpeechConfigOrBuilder() { return synthesizeSpeechConfig_ == null ? com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.getDefaultInstance() : synthesizeSpeechConfig_; } 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 (audioEncoding_ != com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED .getNumber()) { output.writeEnum(1, audioEncoding_); } if (sampleRateHertz_ != 0) { output.writeInt32(2, sampleRateHertz_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getSynthesizeSpeechConfig()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (audioEncoding_ != com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, audioEncoding_); } if (sampleRateHertz_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, sampleRateHertz_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getSynthesizeSpeechConfig()); } 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.OutputAudioConfig)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.OutputAudioConfig other = (com.google.cloud.dialogflow.v2beta1.OutputAudioConfig) obj; if (audioEncoding_ != other.audioEncoding_) return false; if (getSampleRateHertz() != other.getSampleRateHertz()) return false; if (hasSynthesizeSpeechConfig() != other.hasSynthesizeSpeechConfig()) return false; if (hasSynthesizeSpeechConfig()) { if (!getSynthesizeSpeechConfig().equals(other.getSynthesizeSpeechConfig())) 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) + AUDIO_ENCODING_FIELD_NUMBER; hash = (53 * hash) + audioEncoding_; hash = (37 * hash) + SAMPLE_RATE_HERTZ_FIELD_NUMBER; hash = (53 * hash) + getSampleRateHertz(); if (hasSynthesizeSpeechConfig()) { hash = (37 * hash) + SYNTHESIZE_SPEECH_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getSynthesizeSpeechConfig().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig 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.OutputAudioConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig 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.OutputAudioConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig 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.OutputAudioConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig 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.OutputAudioConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig 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.OutputAudioConfig 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.OutputAudioConfig 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.OutputAudioConfig 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> * Instructs the speech synthesizer how to generate the output audio content. * If this audio config is supplied in a request, it overrides all existing * text-to-speech settings applied to the agent. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.OutputAudioConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.OutputAudioConfig) com.google.cloud.dialogflow.v2beta1.OutputAudioConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.AudioConfigProto .internal_static_google_cloud_dialogflow_v2beta1_OutputAudioConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.AudioConfigProto .internal_static_google_cloud_dialogflow_v2beta1_OutputAudioConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.class, com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getSynthesizeSpeechConfigFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; audioEncoding_ = 0; sampleRateHertz_ = 0; synthesizeSpeechConfig_ = null; if (synthesizeSpeechConfigBuilder_ != null) { synthesizeSpeechConfigBuilder_.dispose(); synthesizeSpeechConfigBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.AudioConfigProto .internal_static_google_cloud_dialogflow_v2beta1_OutputAudioConfig_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioConfig getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioConfig build() { com.google.cloud.dialogflow.v2beta1.OutputAudioConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioConfig buildPartial() { com.google.cloud.dialogflow.v2beta1.OutputAudioConfig result = new com.google.cloud.dialogflow.v2beta1.OutputAudioConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dialogflow.v2beta1.OutputAudioConfig result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.audioEncoding_ = audioEncoding_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sampleRateHertz_ = sampleRateHertz_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.synthesizeSpeechConfig_ = synthesizeSpeechConfigBuilder_ == null ? synthesizeSpeechConfig_ : synthesizeSpeechConfigBuilder_.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.OutputAudioConfig) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.OutputAudioConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.OutputAudioConfig other) { if (other == com.google.cloud.dialogflow.v2beta1.OutputAudioConfig.getDefaultInstance()) return this; if (other.audioEncoding_ != 0) { setAudioEncodingValue(other.getAudioEncodingValue()); } if (other.getSampleRateHertz() != 0) { setSampleRateHertz(other.getSampleRateHertz()); } if (other.hasSynthesizeSpeechConfig()) { mergeSynthesizeSpeechConfig(other.getSynthesizeSpeechConfig()); } 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: { audioEncoding_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { sampleRateHertz_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage( getSynthesizeSpeechConfigFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private int audioEncoding_ = 0; /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for audioEncoding. */ @java.lang.Override public int getAudioEncodingValue() { return audioEncoding_; } /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for audioEncoding to set. * @return This builder for chaining. */ public Builder setAudioEncodingValue(int value) { audioEncoding_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The audioEncoding. */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding getAudioEncoding() { com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding result = com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.forNumber(audioEncoding_); return result == null ? com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding.UNRECOGNIZED : result; } /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The audioEncoding to set. * @return This builder for chaining. */ public Builder setAudioEncoding(com.google.cloud.dialogflow.v2beta1.OutputAudioEncoding value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; audioEncoding_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Required. Audio encoding of the synthesized audio content. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.OutputAudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearAudioEncoding() { bitField0_ = (bitField0_ & ~0x00000001); audioEncoding_ = 0; onChanged(); return this; } private int sampleRateHertz_; /** * * * <pre> * The synthesis sample rate (in hertz) for this audio. If not * provided, then the synthesizer will use the default sample rate based on * the audio encoding. If this is different from the voice's natural sample * rate, then the synthesizer will honor this request by converting to the * desired sample rate (which might result in worse audio quality). * </pre> * * <code>int32 sample_rate_hertz = 2;</code> * * @return The sampleRateHertz. */ @java.lang.Override public int getSampleRateHertz() { return sampleRateHertz_; } /** * * * <pre> * The synthesis sample rate (in hertz) for this audio. If not * provided, then the synthesizer will use the default sample rate based on * the audio encoding. If this is different from the voice's natural sample * rate, then the synthesizer will honor this request by converting to the * desired sample rate (which might result in worse audio quality). * </pre> * * <code>int32 sample_rate_hertz = 2;</code> * * @param value The sampleRateHertz to set. * @return This builder for chaining. */ public Builder setSampleRateHertz(int value) { sampleRateHertz_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The synthesis sample rate (in hertz) for this audio. If not * provided, then the synthesizer will use the default sample rate based on * the audio encoding. If this is different from the voice's natural sample * rate, then the synthesizer will honor this request by converting to the * desired sample rate (which might result in worse audio quality). * </pre> * * <code>int32 sample_rate_hertz = 2;</code> * * @return This builder for chaining. */ public Builder clearSampleRateHertz() { bitField0_ = (bitField0_ & ~0x00000002); sampleRateHertz_ = 0; onChanged(); return this; } private com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesizeSpeechConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.Builder, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfigOrBuilder> synthesizeSpeechConfigBuilder_; /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> * * @return Whether the synthesizeSpeechConfig field is set. */ public boolean hasSynthesizeSpeechConfig() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> * * @return The synthesizeSpeechConfig. */ public com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig getSynthesizeSpeechConfig() { if (synthesizeSpeechConfigBuilder_ == null) { return synthesizeSpeechConfig_ == null ? com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.getDefaultInstance() : synthesizeSpeechConfig_; } else { return synthesizeSpeechConfigBuilder_.getMessage(); } } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public Builder setSynthesizeSpeechConfig( com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig value) { if (synthesizeSpeechConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } synthesizeSpeechConfig_ = value; } else { synthesizeSpeechConfigBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public Builder setSynthesizeSpeechConfig( com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.Builder builderForValue) { if (synthesizeSpeechConfigBuilder_ == null) { synthesizeSpeechConfig_ = builderForValue.build(); } else { synthesizeSpeechConfigBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public Builder mergeSynthesizeSpeechConfig( com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig value) { if (synthesizeSpeechConfigBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && synthesizeSpeechConfig_ != null && synthesizeSpeechConfig_ != com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig .getDefaultInstance()) { getSynthesizeSpeechConfigBuilder().mergeFrom(value); } else { synthesizeSpeechConfig_ = value; } } else { synthesizeSpeechConfigBuilder_.mergeFrom(value); } if (synthesizeSpeechConfig_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public Builder clearSynthesizeSpeechConfig() { bitField0_ = (bitField0_ & ~0x00000004); synthesizeSpeechConfig_ = null; if (synthesizeSpeechConfigBuilder_ != null) { synthesizeSpeechConfigBuilder_.dispose(); synthesizeSpeechConfigBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.Builder getSynthesizeSpeechConfigBuilder() { bitField0_ |= 0x00000004; onChanged(); return getSynthesizeSpeechConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ public com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfigOrBuilder getSynthesizeSpeechConfigOrBuilder() { if (synthesizeSpeechConfigBuilder_ != null) { return synthesizeSpeechConfigBuilder_.getMessageOrBuilder(); } else { return synthesizeSpeechConfig_ == null ? com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.getDefaultInstance() : synthesizeSpeechConfig_; } } /** * * * <pre> * Configuration of how speech should be synthesized. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig synthesize_speech_config = 3; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.Builder, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfigOrBuilder> getSynthesizeSpeechConfigFieldBuilder() { if (synthesizeSpeechConfigBuilder_ == null) { synthesizeSpeechConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfig.Builder, com.google.cloud.dialogflow.v2beta1.SynthesizeSpeechConfigOrBuilder>( getSynthesizeSpeechConfig(), getParentForChildren(), isClean()); synthesizeSpeechConfig_ = null; } return synthesizeSpeechConfigBuilder_; } @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.OutputAudioConfig) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.OutputAudioConfig) private static final com.google.cloud.dialogflow.v2beta1.OutputAudioConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.OutputAudioConfig(); } public static com.google.cloud.dialogflow.v2beta1.OutputAudioConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<OutputAudioConfig> PARSER = new com.google.protobuf.AbstractParser<OutputAudioConfig>() { @java.lang.Override public OutputAudioConfig 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<OutputAudioConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<OutputAudioConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.OutputAudioConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ofbiz-plugins
35,307
ebay/src/main/java/org/apache/ofbiz/ebay/EbayHelper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ofbiz.ebay; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.sql.Timestamp; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilURL; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.base.util.UtilXml; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.entity.util.EntityUtilProperties; import org.apache.ofbiz.order.shoppingcart.ShoppingCart; import org.apache.ofbiz.party.contact.ContactHelper; import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; public class EbayHelper { private static final String CONFIG_FILE_NAME = "ebayExport.properties"; private static final String MODULE = EbayHelper.class.getName(); private static final String RESOURCE = "EbayUiLabels"; public static Map<String, Object> buildEbayConfig(Map<String, Object> context, Delegator delegator) { Map<String, Object> buildEbayConfigContext = new HashMap<>(); Locale locale = (Locale) context.get("locale"); String productStoreId = (String) context.get("productStoreId"); if (UtilValidate.isNotEmpty(productStoreId)) { GenericValue eBayConfig = null; try { eBayConfig = EntityQuery.use(delegator).from("EbayConfig").where(UtilMisc.toMap("productStoreId", productStoreId)).queryOne(); } catch (GenericEntityException e) { String errMsg = UtilProperties.getMessage(RESOURCE, "buildEbayConfig.unableToFindEbayConfig" + e.getMessage(), locale); return ServiceUtil.returnError(errMsg); } if (eBayConfig != null) { buildEbayConfigContext.put("devID", eBayConfig.getString("devId")); buildEbayConfigContext.put("appID", eBayConfig.getString("appId")); buildEbayConfigContext.put("certID", eBayConfig.getString("certId")); buildEbayConfigContext.put("token", eBayConfig.getString("token")); buildEbayConfigContext.put("compatibilityLevel", eBayConfig.getString("compatibilityLevel")); buildEbayConfigContext.put("siteID", eBayConfig.getString("siteId")); buildEbayConfigContext.put("xmlGatewayUri", eBayConfig.getString("xmlGatewayUri")); buildEbayConfigContext.put("apiServerUrl", eBayConfig.getString("xmlGatewayUri")); } } else { buildEbayConfigContext.put("devID", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.devID", delegator)); buildEbayConfigContext.put("appID", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.appID", delegator)); buildEbayConfigContext.put("certID", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.certID", delegator)); buildEbayConfigContext.put("token", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.token", delegator)); buildEbayConfigContext.put("compatibilityLevel", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.compatibilityLevel", delegator)); buildEbayConfigContext.put("siteID", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.siteID", delegator)); buildEbayConfigContext.put("xmlGatewayUri", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.xmlGatewayUri", delegator)); buildEbayConfigContext.put("apiServerUrl", EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.xmlGatewayUri", delegator)); } return buildEbayConfigContext; } public static void appendRequesterCredentials(Element elem, Document doc, String token) { Element requesterCredentialsElem = UtilXml.addChildElement(elem, "RequesterCredentials", doc); UtilXml.addChildElementValue(requesterCredentialsElem, "eBayAuthToken", token, doc); } public static Map<String, Object> postItem(String postItemsUrl, StringBuffer generatedXmlData, String devID, String appID, String certID, String callName, String compatibilityLevel, String siteID) throws IOException { if (Debug.verboseOn()) { Debug.logVerbose("Request of " + callName + " To eBay:\n" + generatedXmlData.toString(), MODULE); } HttpURLConnection connection = (HttpURLConnection) (UtilURL.fromUrlString(postItemsUrl)).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("X-EBAY-API-COMPATIBILITY-LEVEL", compatibilityLevel); connection.setRequestProperty("X-EBAY-API-DEV-NAME", devID); connection.setRequestProperty("X-EBAY-API-APP-NAME", appID); connection.setRequestProperty("X-EBAY-API-CERT-NAME", certID); connection.setRequestProperty("X-EBAY-API-CALL-NAME", callName); connection.setRequestProperty("X-EBAY-API-SITEID", siteID); connection.setRequestProperty("Content-Type", "text/xml"); OutputStream outputStream = connection.getOutputStream(); outputStream.write(generatedXmlData.toString().getBytes()); outputStream.close(); int responseCode = connection.getResponseCode(); InputStream inputStream = null; Map<String, Object> result = new HashMap<>(); String response = null; if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); response = EbayHelper.toString(inputStream); result = ServiceUtil.returnSuccess(response); } else { inputStream = connection.getErrorStream(); result = ServiceUtil.returnFailure(EbayHelper.toString(inputStream)); } if (Debug.verboseOn()) { Debug.logVerbose("Response of " + callName + " From eBay:\n" + response, MODULE); } return result; } public static String convertDate(String dateIn, String fromDateFormat, String toDateFormat) { String dateOut; try { SimpleDateFormat formatIn = new SimpleDateFormat(fromDateFormat); SimpleDateFormat formatOut = new SimpleDateFormat(toDateFormat); Date data = formatIn.parse(dateIn, new ParsePosition(0)); dateOut = formatOut.format(data); } catch (Exception e) { dateOut = null; } return dateOut; } public static String toString(InputStream inputStream) throws IOException { String string; StringBuilder outputBuilder = new StringBuilder(); if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } return outputBuilder.toString(); } public static void setShipmentMethodType(ShoppingCart cart, String shippingService, String productStoreId, Delegator delegator) { String partyId = "_NA_"; String shipmentMethodTypeId = "NO_SHIPPING"; try { GenericValue ebayShippingMethod = EntityQuery.use(delegator).from("EbayShippingMethod").where("shipmentMethodName", shippingService, "productStoreId", productStoreId).queryOne(); if (ebayShippingMethod != null) { partyId = ebayShippingMethod.getString("carrierPartyId"); shipmentMethodTypeId = ebayShippingMethod.getString("shipmentMethodTypeId"); } else { //Find ebay shipping method on the basis of shipmentMethodName so that we can create new record with productStorId, // EbayShippingMethod data is required for atleast one productStore ebayShippingMethod = EntityQuery.use(delegator).from("EbayShippingMethod").where("shipmentMethodName", shippingService).queryFirst(); ebayShippingMethod.put("productStoreId", productStoreId); delegator.create(ebayShippingMethod); partyId = ebayShippingMethod.getString("carrierPartyId"); shipmentMethodTypeId = ebayShippingMethod.getString("shipmentMethodTypeId"); } } catch (GenericEntityException e) { Debug.logInfo("Unable to find EbayShippingMethod", MODULE); } cart.setAllCarrierPartyId(partyId); cart.setAllShipmentMethodTypeId(shipmentMethodTypeId); } public static boolean createPaymentFromPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, String externalId, Timestamp orderDate, BigDecimal amount, String partyIdFrom) { List<GenericValue> paymentPreferences = null; try { paymentPreferences = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId, "statusId", "PAYMENT_RECEIVED", "paymentMethodTypeId", "EXT_EBAY").queryList(); if (UtilValidate.isNotEmpty(paymentPreferences)) { Iterator<GenericValue> i = paymentPreferences.iterator(); while (i.hasNext()) { GenericValue pref = i.next(); boolean okay = createPayment(dispatcher, userLogin, pref, orderId, externalId, orderDate, partyIdFrom); if (!okay) { return false; } } } else { paymentPreferences = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED", "paymentMethodTypeId", "EXT_EBAY").queryList(); if (UtilValidate.isNotEmpty(paymentPreferences)) { Iterator<GenericValue> i = paymentPreferences.iterator(); while (i.hasNext()) { GenericValue pref = i.next(); if (UtilValidate.isNotEmpty(amount)) { pref.set("statusId", "PAYMENT_RECEIVED"); pref.set("maxAmount", amount); pref.store(); } boolean okay = createPayment(dispatcher, userLogin, pref, orderId, externalId, orderDate, partyIdFrom); if (!okay) { return false; } } } } } catch (GenericEntityException gee) { Debug.logError(gee, "Cannot get payment preferences for order #" + orderId, MODULE); return false; } return true; } public static boolean createPayment(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, String orderId, String externalId, Timestamp orderDate, String partyIdFrom) { try { Delegator delegator = paymentPreference.getDelegator(); // create the PaymentGatewayResponse String responseId = delegator.getNextSeqId("PaymentGatewayResponse"); GenericValue response = delegator.makeValue("PaymentGatewayResponse"); response.set("paymentGatewayResponseId", responseId); response.set("paymentServiceTypeEnumId", "PRDS_PAY_EXTERNAL"); response.set("orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId")); response.set("paymentMethodTypeId", paymentPreference.get("paymentMethodTypeId")); response.set("paymentMethodId", paymentPreference.get("paymentMethodId")); response.set("amount", paymentPreference.get("maxAmount")); response.set("referenceNum", externalId); response.set("transactionDate", orderDate); delegator.createOrStore(response); // create the payment Map<String, Object> results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "paymentFromId", partyIdFrom, "paymentRefNum", externalId, "comments", "Payment receive via eBay")); if (ServiceUtil.isError(results)) { Debug.logError(ServiceUtil.getErrorMessage(results) + " - " + results, MODULE); } if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) { if ((results != null)) { Debug.logError((String) results.get(ModelService.ERROR_MESSAGE), MODULE); } return false; } return true; } catch (GenericEntityException | GenericServiceException e) { Debug.logError(e, "Failed to create the payment for order " + orderId, MODULE); return false; } } public static GenericValue makeOrderAdjustment(Delegator delegator, String orderAdjustmentTypeId, String orderId, String orderItemSeqId, String shipGroupSeqId, double amount, double sourcePercentage) { GenericValue orderAdjustment = null; try { if (UtilValidate.isNotEmpty(orderItemSeqId)) { orderItemSeqId = "_NA_"; } if (UtilValidate.isNotEmpty(shipGroupSeqId)) { shipGroupSeqId = "_NA_"; } Map<String, Object> inputMap = UtilMisc.toMap("orderAdjustmentTypeId", orderAdjustmentTypeId, "orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId, "amount", new BigDecimal(amount)); if (sourcePercentage != 0) { inputMap.put("sourcePercentage", sourcePercentage); } orderAdjustment = delegator.makeValue("OrderAdjustment", inputMap); } catch (Exception e) { Debug.logError(e, "Failed to made order adjustment for order " + orderId, MODULE); } return orderAdjustment; } public static String createCustomerParty(LocalDispatcher dispatcher, String name, GenericValue userLogin) { String partyId = null; try { if (UtilValidate.isNotEmpty(name) && userLogin != null) { if (Debug.verboseOn()) { Debug.logVerbose("Creating Customer Party: " + name, MODULE); } // Try to split the lastname from the firstname String firstName = ""; String lastName = ""; int pos = name.indexOf(" "); if (pos >= 0) { firstName = name.substring(0, pos); lastName = name.substring(pos + 1); } else { lastName = name; } Map<String, Object> summaryResult = dispatcher.runSync("createPerson", UtilMisc.<String, Object>toMap("description", name, "firstName", firstName, "lastName", lastName, "userLogin", userLogin, "comments", "Created via eBay")); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); return null; } partyId = (String) summaryResult.get("partyId"); if (Debug.verboseOn()) { Debug.logVerbose("Created Customer Party: " + partyId, MODULE); } } } catch (GenericServiceException e) { Debug.logError(e, "Failed to createPerson", MODULE); } return partyId; } public static String createAddress(LocalDispatcher dispatcher, String partyId, GenericValue userLogin, String contactMechPurposeTypeId, Map<String, Object> address) { Debug.logInfo("Creating postal address with input map: " + address, MODULE); String contactMechId = null; try { Map<String, Object> context = new HashMap<>(); context.put("partyId", partyId); context.put("toName", address.get("buyerName")); context.put("address1", address.get("shippingAddressStreet1")); context.put("address2", address.get("shippingAddressStreet2")); context.put("postalCode", address.get("shippingAddressPostalCode")); context.put("userLogin", userLogin); context.put("contactMechPurposeTypeId", contactMechPurposeTypeId); String country = (String) address.get("shippingAddressCountry"); String state = (String) address.get("shippingAddressStateOrProvince"); String city = (String) address.get("shippingAddressCityName"); correctCityStateCountry(dispatcher, context, city, state, country); Map<String, Object> summaryResult = dispatcher.runSync("createPartyPostalAddress", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); return null; } contactMechId = (String) summaryResult.get("contactMechId"); // Set also as a billing address context = new HashMap<>(); context.put("partyId", partyId); context.put("contactMechId", contactMechId); context.put("contactMechPurposeTypeId", "BILLING_LOCATION"); context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyContactMechPurpose", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); return null; } } catch (GenericServiceException e) { Debug.logError(e, "Failed to createAddress", MODULE); } return contactMechId; } public static void correctCityStateCountry(LocalDispatcher dispatcher, Map<String, Object> map, String city, String state, String country) { try { String geoCode = null; Debug.logInfo("correctCityStateCountry params: " + city + ", " + state + ", " + country, MODULE); if (UtilValidate.isEmpty(country)) { geoCode = "US"; } country = country.toUpperCase(); if (country.indexOf("UNITED STATES") > -1 || country.indexOf("USA") > -1) { geoCode = "US"; } if (UtilValidate.isEmpty(geoCode)) { geoCode = country; } Debug.logInfo("GeoCode: " + geoCode, MODULE); Map<String, Object> outMap = getCountryGeoId(dispatcher.getDelegator(), geoCode); String geoId = (String) outMap.get("geoId"); if (UtilValidate.isEmpty(geoId)) { geoId = "USA"; } map.put("countryGeoId", geoId); country = geoId; Debug.logInfo("Country geoid: " + geoId, MODULE); if ("USA".equals(geoId) || "CAN".equals(geoId)) { if (UtilValidate.isNotEmpty(state)) { map.put("stateProvinceGeoId", state.toUpperCase()); } map.put("city", city); } else { map.put("city", city + ", " + state); } Debug.logInfo("State geoid: " + state, MODULE); } catch (Exception e) { Debug.logError(e, "Failed to correctCityStateCountry", MODULE); } } public static String createPartyPhone(LocalDispatcher dispatcher, String partyId, String phoneNumber, GenericValue userLogin) { Map<String, Object> summaryResult = new HashMap<>(); Map<String, Object> context = new HashMap<>(); String phoneContactMechId = null; try { context.put("contactNumber", phoneNumber); context.put("partyId", partyId); context.put("userLogin", userLogin); context.put("contactMechPurposeTypeId", "PHONE_SHIPPING"); summaryResult = dispatcher.runSync("createPartyTelecomNumber", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); return null; } phoneContactMechId = (String) summaryResult.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e, "Failed to createPartyPhone", MODULE); } return phoneContactMechId; } public static String createPartyEmail(LocalDispatcher dispatcher, String partyId, String email, GenericValue userLogin) { Map<String, Object> context = new HashMap<>(); Map<String, Object> summaryResult = new HashMap<>(); String emailContactMechId = null; try { if (UtilValidate.isNotEmpty(email)) { context.clear(); context.put("emailAddress", email); context.put("userLogin", userLogin); context.put("contactMechTypeId", "EMAIL_ADDRESS"); summaryResult = dispatcher.runSync("createEmailAddress", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); } emailContactMechId = (String) summaryResult.get("contactMechId"); context.clear(); context.put("partyId", partyId); context.put("contactMechId", emailContactMechId); context.put("contactMechPurposeTypeId", "OTHER_EMAIL"); context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyContactMech", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); } } } catch (GenericServiceException e) { Debug.logError(e, "Failed to createPartyEmail", MODULE); } return emailContactMechId; } public static void createEbayCustomer(LocalDispatcher dispatcher, String partyId, String ebayUserIdBuyer, String eias, GenericValue userLogin) { Map<String, Object> context = new HashMap<>(); Map<String, Object> summaryResult = new HashMap<>(); if (UtilValidate.isNotEmpty(eias)) { try { context.put("partyId", partyId); context.put("attrName", "EBAY_BUYER_EIAS"); context.put("attrValue", eias); context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyAttribute", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); } } catch (GenericServiceException e) { Debug.logError(e, "Failed to create eBay EIAS party attribute"); } context.clear(); summaryResult.clear(); } if (UtilValidate.isNotEmpty(ebayUserIdBuyer)) { try { context.put("partyId", partyId); context.put("attrName", "EBAY_BUYER_USER_ID"); context.put("attrValue", ebayUserIdBuyer); context.put("userLogin", userLogin); summaryResult = dispatcher.runSync("createPartyAttribute", context); if (ServiceUtil.isError(summaryResult)) { Debug.logError(ServiceUtil.getErrorMessage(summaryResult) + " - " + summaryResult, MODULE); } } catch (GenericServiceException e) { Debug.logError(e, "Failed to create eBay userId party attribute"); } } } public static Map<String, Object> getCountryGeoId(Delegator delegator, String geoCode) { GenericValue geo = null; try { Debug.logInfo("geocode: " + geoCode, MODULE); geo = EntityQuery.use(delegator).from("Geo").where("geoCode", geoCode.toUpperCase(), "geoTypeId", "COUNTRY").queryFirst(); Debug.logInfo("Found a geo entity " + geo, MODULE); if (UtilValidate.isEmpty(geo)) { geo = delegator.makeValue("Geo"); geo.set("geoId", geoCode + "_IMPORTED"); geo.set("geoTypeId", "COUNTRY"); geo.set("geoName", geoCode + "_IMPORTED"); geo.set("geoCode", geoCode + "_IMPORTED"); geo.set("abbreviation", geoCode + "_IMPORTED"); delegator.create(geo); Debug.logInfo("Creating new geo entity: " + geo, MODULE); } } catch (GenericEntityException e) { String errMsg = "Failed to find/setup geo id"; Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("geoId", geo.get("geoId")); return result; } public static String setShippingAddressContactMech(LocalDispatcher dispatcher, Delegator delegator, GenericValue party, GenericValue userLogin, Map<String, Object> context) { String contactMechId = null; String partyId = (String) party.get("partyId"); // find all contact mechs for this party with a shipping location // purpose. Collection<GenericValue> shippingLocations = ContactHelper.getContactMechByPurpose(party, "SHIPPING_LOCATION", false); // check them to see if one matches Iterator<GenericValue> shippingLocationsIterator = shippingLocations.iterator(); while (shippingLocationsIterator.hasNext()) { GenericValue shippingLocation = shippingLocationsIterator.next(); contactMechId = shippingLocation.getString("contactMechId"); GenericValue postalAddress; try { // get the postal address for this contact mech postalAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", contactMechId).queryOne(); // match values to compare by modifying them the same way they // were when they were created String country = ((String) context.get("shippingAddressCountry")).toUpperCase(); String state = ((String) context.get("shippingAddressStateOrProvince")).toUpperCase(); String city = (String) context.get("shippingAddressCityName"); correctCityStateCountry(dispatcher, context, city, state, country); // TODO: The following comparison does not consider the To Name // or Attn: lines of the address. // // now compare values. If all fields match, that's our shipping // address. Return the related contact mech id. if (context.get("shippingAddressStreet1").toString().equals((postalAddress.get("address1").toString())) && context.get("city").toString().equals((postalAddress.get("city").toString())) && context.get("stateProvinceGeoId").toString().equals((postalAddress.get("stateProvinceGeoId").toString())) && context.get("countryGeoId").toString().equals((postalAddress.get("countryGeoId").toString())) && context.get("shippingAddressPostalCode").toString().equals((postalAddress.get("postalCode").toString()))) { return contactMechId; } } catch (Exception e) { Debug.logError(e, "Problem with verifying postal addresses for contactMechId " + contactMechId + ".", MODULE); } } // none of the existing contact mechs/postal addresses match (or none // were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", MODULE); return createAddress(dispatcher, partyId, userLogin, "SHIPPING_LOCATION", context); } public static String setEmailContactMech(LocalDispatcher dispatcher, Delegator delegator, GenericValue party, GenericValue userLogin, Map<String, Object> context) { String contactMechId = null; String partyId = (String) party.get("partyId"); // find all contact mechs for this party with a email address purpose. Collection<GenericValue> emailAddressContactMechs = ContactHelper.getContactMechByPurpose(party, "OTHER_EMAIL", false); // check them to see if one matches Iterator<GenericValue> emailAddressesContactMechsIterator = emailAddressContactMechs.iterator(); while (emailAddressesContactMechsIterator.hasNext()) { GenericValue emailAddressContactMech = emailAddressesContactMechsIterator.next(); contactMechId = emailAddressContactMech.getString("contactMechId"); // now compare values. If one matches, that's our email address. // Return the related contact mech id. if (context.get("emailBuyer").toString().equals((emailAddressContactMech.get("infoString").toString()))) { return contactMechId; } } // none of the existing contact mechs/email addresses match (or none // were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", MODULE); return createPartyEmail(dispatcher, partyId, (String) context.get("emailBuyer"), userLogin); } public static String setPhoneContactMech(LocalDispatcher dispatcher, Delegator delegator, GenericValue party, GenericValue userLogin, Map<String, Object> context) { String contactMechId = null; String partyId = (String) party.get("partyId"); // find all contact mechs for this party with a telecom number purpose. Collection<GenericValue> phoneNumbers = ContactHelper.getContactMechByPurpose(party, "PHONE_SHIPPING", false); // check them to see if one matches Iterator<GenericValue> phoneNumbersIterator = phoneNumbers.iterator(); while (phoneNumbersIterator.hasNext()) { GenericValue phoneNumberContactMech = phoneNumbersIterator.next(); contactMechId = phoneNumberContactMech.getString("contactMechId"); GenericValue phoneNumber; try { // get the phone number for this contact mech phoneNumber = EntityQuery.use(delegator).from("TelecomNumber").where("contactMechId", contactMechId).queryOne(); // now compare values. If one matches, that's our phone number. // Return the related contact mech id. if (context.get("shippingAddressPhone").toString() .equals((phoneNumber.get("contactNumber").toString()))) { return contactMechId; } } catch (GenericEntityException e) { Debug.logError("Problem with verifying phone number for contactMechId " + contactMechId + ".", MODULE); } } // none of the existing contact mechs/email addresses match (or none // were found). Create a new one and return the related contact mech id. Debug.logInfo("Unable to find matching postal address for partyId " + partyId + ". Creating a new one.", MODULE); return createPartyPhone(dispatcher, partyId, (String) context.get("shippingAddressPhone"), userLogin); } public static String retrieveProductIdFromTitle(Delegator delegator, String title) { String productId = ""; try { // First try to get an exact match: title == internalName List<GenericValue> products = EntityQuery.use(delegator).from("Product").where("internalName", title).queryList(); if (UtilValidate.isNotEmpty(products) && products.size() == 1) { productId = (String) (products.get(0)).get("productId"); } // If it fails, attempt to get the product id from the first word of the title if (UtilValidate.isEmpty(productId)) { String titleFirstWord = null; if (title != null && title.indexOf(' ') != -1) { titleFirstWord = title.substring(0, title.indexOf(' ')); } if (UtilValidate.isNotEmpty(titleFirstWord)) { GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", titleFirstWord).queryOne(); if (product != null) { productId = product.getString("productId"); } } } } catch (GenericEntityException e) { productId = ""; } return productId; } }
google/graphicsfuzz
34,716
generator/src/test/java/com/graphicsfuzz/generator/transformation/DonateLiveCodeTransformationTest.java
/* * Copyright 2018 The GraphicsFuzz Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphicsfuzz.generator.transformation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.graphicsfuzz.common.ast.IParentMap; import com.graphicsfuzz.common.ast.TranslationUnit; import com.graphicsfuzz.common.ast.decl.FunctionDefinition; import com.graphicsfuzz.common.ast.decl.FunctionPrototype; import com.graphicsfuzz.common.ast.decl.Initializer; import com.graphicsfuzz.common.ast.decl.VariableDeclInfo; import com.graphicsfuzz.common.ast.decl.VariablesDeclaration; import com.graphicsfuzz.common.ast.expr.ArrayIndexExpr; import com.graphicsfuzz.common.ast.expr.BinOp; import com.graphicsfuzz.common.ast.expr.BinaryExpr; import com.graphicsfuzz.common.ast.expr.FunctionCallExpr; import com.graphicsfuzz.common.ast.expr.VariableIdentifierExpr; import com.graphicsfuzz.common.ast.stmt.BlockStmt; import com.graphicsfuzz.common.ast.stmt.DeclarationStmt; import com.graphicsfuzz.common.ast.stmt.DiscardStmt; import com.graphicsfuzz.common.ast.stmt.ForStmt; import com.graphicsfuzz.common.ast.stmt.IfStmt; import com.graphicsfuzz.common.ast.stmt.Stmt; import com.graphicsfuzz.common.ast.stmt.SwitchStmt; import com.graphicsfuzz.common.ast.type.BasicType; import com.graphicsfuzz.common.ast.type.Type; import com.graphicsfuzz.common.ast.type.VoidType; import com.graphicsfuzz.common.ast.visitors.CheckPredicateVisitor; import com.graphicsfuzz.common.glslversion.ShadingLanguageVersion; import com.graphicsfuzz.common.transformreduce.GlslShaderJob; import com.graphicsfuzz.common.transformreduce.ShaderJob; import com.graphicsfuzz.common.typing.ScopeEntry; import com.graphicsfuzz.common.typing.ScopeTrackingVisitor; import com.graphicsfuzz.common.typing.Typer; import com.graphicsfuzz.common.util.IRandom; import com.graphicsfuzz.common.util.ParseHelper; import com.graphicsfuzz.common.util.PipelineInfo; import com.graphicsfuzz.common.util.RandomWrapper; import com.graphicsfuzz.common.util.ShaderJobFileOperations; import com.graphicsfuzz.common.util.ShaderKind; import com.graphicsfuzz.generator.transformation.donation.DonationContext; import com.graphicsfuzz.generator.transformation.injection.BlockInjectionPoint; import com.graphicsfuzz.generator.transformation.injection.IInjectionPoint; import com.graphicsfuzz.generator.transformation.injection.InjectionPoints; import com.graphicsfuzz.generator.util.GenerationParams; import com.graphicsfuzz.generator.util.TransformationProbabilities; import com.graphicsfuzz.server.thrift.ImageJob; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class DonateLiveCodeTransformationTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); private DonateLiveCodeTransformation getDummyTransformationObject() { return new DonateLiveCodeTransformation(IRandom::nextBoolean, testFolder.getRoot(), GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); } @Test public void adaptTranslationUnitForSpecificDonationDiscardRemoved() throws Exception { final TranslationUnit tu = ParseHelper.parse("#version 320 es\n" + "void main() {\n" + " discard;\n" + "}\n"); final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); dlc.adaptTranslationUnitForSpecificDonation(tu, new RandomWrapper(0)); assertFalse(new CheckPredicateVisitor() { @Override public void visitDiscardStmt(DiscardStmt discardStmt) { predicateHolds(); } }.test(tu)); } @Test public void prepareStatementToDonateTopLevelBreakRemoved() throws Exception { // Checks that a top-level 'break' gets removed, even when injecting into a loop or // switch. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " for (int i = 0; i < 10; i ++)\n" + " if (i > 5) break;\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " for(int i = 0; i < 100; i++) {\n" + " switch (i) {\n" + " case 0:\n" + " i++;\n" + " default:\n" + " i++;\n" + " }\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = ((ForStmt) donor.getMainFunction().getBody().getStmt(0)).getBody() .clone(); assert toDonate instanceof IfStmt; final DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_310); assertEquals("{\n" + " if(i > 5)\n" + " 1;\n" + "}\n", donated.getText()); } } @Test public void prepareStatementToDonateTopLevelContinueRemoved() throws Exception { // Checks that a top-level 'continue' gets removed, even when injecting into a loop. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 100\n" + "void main() {\n" + " for (int i = 0; i < 10; i ++)\n" + " if (i > 5) continue;\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 100\n" + "void main() {\n" + " for(int i = 0; i < 100; i++) {\n" + " 1;\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = ((ForStmt) donor.getMainFunction().getBody().getStmt(0)).getBody() .clone(); assert toDonate instanceof IfStmt; final DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_100); assertEquals("{\n" + " if(i > 5)\n" + " 1;\n" + "}\n", donated.getText()); } } @Test public void prepareStatementToDonateTopLevelCaseAndDefaultRemoved() throws Exception { // Checks that top-level 'case' and 'default' labels get removed, even when injecting into // a switch. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " int x = 3;\n" + " switch (x) {\n" + " case 0:\n" + " x++;\n" + " default:\n" + " x++;\n" + " }\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " switch (0) {\n" + " case 1:\n" + " 1;\n" + " default:\n" + " 2;\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = ((SwitchStmt) donor.getMainFunction().getBody().getStmt(1)).getBody() .clone(); final DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_310); assertEquals("{\n" + " {\n" + " 1;\n" + " x ++;\n" + " 1;\n" + " x ++;\n" + " }\n" + "}\n", donated.getText()); } } @Test public void prepareStatementToDonateBreakFromLoopKept() throws Exception { // Checks that a 'break' in a loop gets kept if the whole loop is donated. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 100\n" + "void main() {\n" + " for (int i = 0; i < 10; i ++)\n" + " if (i > 5) break;\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 100\n" + "void main() {\n" + " ;\n" + " for(int i = 0; i < 100; i++) {\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = donor.getMainFunction().getBody().getStmt(0) .clone(); assert toDonate instanceof ForStmt; final DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_100); assertEquals("{\n" + " for(int i = 0; i < 10; i ++)\n" + " if(i > 5)\n" + " break;\n" + "}\n", donated.getText()); } } @Test public void prepareStatementToDonateSwitchWithBreakAndDefaultKept() throws Exception { // Checks that 'case', 'default' and 'break' occurring in a switch are kept if the whole // switch statement is donated. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " switch (0) {\n" + " case 0:\n" + " 1;\n" + " break;\n" + " default:\n" + " 2;\n" + " }\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 310 es\n" + "void main() {\n" + " ;\n" + " switch (0) {\n" + " case 1:\n" + " 1;\n" + " default:\n" + " 2;\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = donor.getMainFunction().getBody().getStmt(0).clone(); assert toDonate instanceof SwitchStmt; final DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_310); assertEquals("{\n" + " switch(0)\n" + " {\n" + " case 0:\n" + " 1;\n" + " break;\n" + " default:\n" + " 2;\n" + " }\n" + "}\n", donated.getText()); } } @Test public void prepareStatementToDonateContinueInLoopKept() throws Exception { // Checks that a 'continue' in a loop gets kept if the whole loop is donated. final DonateLiveCodeTransformation dlc = getDummyTransformationObject(); final TranslationUnit donor = ParseHelper.parse("#version 100\n" + "void main() {\n" + " for (int i = 0; i < 10; i ++)\n" + " if (i > 5) continue;\n" + "}\n"); final TranslationUnit reference = ParseHelper.parse("#version 100\n" + "void main() {\n" + " ;\n" + " for(int i = 0; i < 100; i++) {\n" + " }\n" + "}\n"); for (IInjectionPoint injectionPoint : new InjectionPoints(reference, new RandomWrapper(0), item -> true).getAllInjectionPoints()) { final Stmt toDonate = donor.getMainFunction().getBody().getStmt(0).clone(); assert toDonate instanceof ForStmt; DonationContext dc = new DonationContext(toDonate, new HashMap<>(), new ArrayList<>(), donor.getMainFunction()); final Stmt donated = dlc.prepareStatementToDonate(injectionPoint, dc, TransformationProbabilities.DEFAULT_PROBABILITIES, new RandomWrapper(0), ShadingLanguageVersion.ESSL_100); assertEquals("{\n" + " for(int i = 0; i < 10; i ++)\n" + " if(i > 5)\n" + " continue;\n" + "}\n", donated.getText()); } } @Test public void checkMutateSpecialCase() throws Exception { // This test aimed to expose an issue, but did not succeed. It's been left // here in the spirit of "why delete a test?" final String reference = "#version 300 es\n" + "void main() {\n" + " int t;\n" + " {\n" + " }\n" + " gl_FragColor = vec4(float(t));\n" + "}\n"; final IRandom generator = new RandomWrapper(0); for (int i = 0; i < 10; i++) { final DonateLiveCodeTransformation donateLiveCode = new DonateLiveCodeTransformation(item -> true, testFolder.getRoot(), GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); final TranslationUnit referenceTu = ParseHelper.parse(reference); BlockInjectionPoint blockInjectionPoint = new ScopeTrackingVisitor() { BlockInjectionPoint blockInjectionPoint; @Override public void visitBlockStmt(BlockStmt stmt) { super.visitBlockStmt(stmt); if (stmt.getNumStmts() == 0) { blockInjectionPoint = new BlockInjectionPoint(stmt, null, getEnclosingFunction(), false, false, getCurrentScope()); } } BlockInjectionPoint getBlockInjectionPoint(TranslationUnit tu) { visit(tu); return blockInjectionPoint; } }.getBlockInjectionPoint(referenceTu); final DeclarationStmt declarationStmt = new DeclarationStmt( new VariablesDeclaration( BasicType.INT, new VariableDeclInfo("a", null, new Initializer( new BinaryExpr( new BinaryExpr( new BinaryExpr( new BinaryExpr( new VariableIdentifierExpr("x1"), new VariableIdentifierExpr("x2"), BinOp.ADD ), new VariableIdentifierExpr("x3"), BinOp.ADD ), new VariableIdentifierExpr("x4"), BinOp.ADD ), new VariableIdentifierExpr("x5"), BinOp.ADD ) ) ))); final Map<String, Type> freeVariables = new HashMap<>(); freeVariables.put("x1", BasicType.INT); freeVariables.put("x2", BasicType.INT); freeVariables.put("x3", BasicType.INT); freeVariables.put("x4", BasicType.INT); freeVariables.put("x5", BasicType.INT); Stmt toDonate = donateLiveCode.prepareStatementToDonate(blockInjectionPoint, new DonationContext( declarationStmt, freeVariables, new ArrayList<>(), new FunctionDefinition(new FunctionPrototype("foo", VoidType.VOID, new ArrayList<>()), null)), TransformationProbabilities.onlyLiveCodeAlwaysSubstitute(), generator, referenceTu.getShadingLanguageVersion()); blockInjectionPoint.inject(toDonate); final IdentityTransformation identityTransformation = new IdentityTransformation(); identityTransformation.apply(referenceTu, TransformationProbabilities.onlyMutateExpressions(), generator, GenerationParams.large(ShaderKind.FRAGMENT, false, true) ); } } @Test public void checkFunctionDeclsUnique() throws Exception { // This test injects live code from a donor into a reference, such that the reference contains // an injected function prototype followed by the injected function definition. We then create a // parent map for the modified reference to ensure that there is no aliasing. I.e. the // function prototype object is not reused in the function definition. final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final File donors = testFolder.newFolder("donors"); final File referenceFile = testFolder.newFile("reference.json"); final File variantFile = testFolder.newFile("variant.json"); { // A call to "bar", which calls "foo" via its prototype (i.e. "foo" is defined after "bar"). final String donorSource = "#version 300 es\n" + "\n" + "int foo(int f);\n" + "\n" + "int bar(int b) {\n" + " return foo(b);\n" + "}\n" + "\n" + "int foo(int f) {\n" + " return f + 1;\n" + "}\n" + "\n" + "void main() {\n" + " bar(1);\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(donorSource) .setUniformsInfo("{}"), new File(donors, "donor.json") ); } { final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(referenceSource) .setUniformsInfo("{}"), referenceFile ); } final ShaderJob referenceShaderJob = fileOps.readShaderJobFile(referenceFile); DonateLiveCodeTransformation transformation = new DonateLiveCodeTransformation(IRandom::nextBoolean, donors, GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); assert referenceShaderJob.getFragmentShader().isPresent(); boolean result = transformation.apply( referenceShaderJob.getFragmentShader().get(), TransformationProbabilities.onlyLiveCodeAlwaysSubstitute(), new RandomWrapper(0), GenerationParams.normal(ShaderKind.FRAGMENT, false, true) ); Assert.assertTrue(result); fileOps.writeShaderJobFile(referenceShaderJob, variantFile); fileOps.areShadersValid(variantFile, true); // Creating a parent map checks that there is no aliasing in the AST. IParentMap.createParentMap(referenceShaderJob.getFragmentShader().get()); } @Test public void verySimpleDonorAndSourceNoPrecision() throws Exception { // This test injects live code from a donor into a reference. The donor and reference contain // almost no code. The modified reference is output and validated. This caught an issue where // shaders without precision qualifiers became invalid because the injected color and coord // variables did not have precision qualifiers. final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final File donors = testFolder.newFolder("donors"); final File referenceFile = testFolder.newFile("reference.json"); final File variantFile = testFolder.newFile("variant.json"); { final String donorSource = "#version 300 es\n" + "void main() {\n" + " 1;\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(donorSource) .setUniformsInfo("{}"), new File(donors, "donor.json") ); } { final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(referenceSource) .setUniformsInfo("{}"), referenceFile ); } final ShaderJob referenceShaderJob = fileOps.readShaderJobFile(referenceFile); DonateLiveCodeTransformation transformation = new DonateLiveCodeTransformation(IRandom::nextBoolean, donors, GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); assert referenceShaderJob.getFragmentShader().isPresent(); boolean result = transformation.apply( referenceShaderJob.getFragmentShader().get(), TransformationProbabilities.onlyLiveCodeAlwaysSubstitute(), new RandomWrapper(0), GenerationParams.normal(ShaderKind.FRAGMENT, false, true) ); Assert.assertTrue(result); fileOps.writeShaderJobFile(referenceShaderJob, variantFile); fileOps.areShadersValid(variantFile, true); // Creating a parent map checks that there is no aliasing in the AST. IParentMap.createParentMap(referenceShaderJob.getFragmentShader().get()); } @Test public void testArrayAccessesAreInBounds() throws Exception { // This checks that array accesses are correctly made in-bounds when injecting live code. final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final File donors = testFolder.newFolder("donors"); final File referenceFile = testFolder.newFile("reference.json"); { // This donor is designed to have a high chance of leading to an array access getting injected // such that the array indexing expression will be a free variable for which a fuzzed initial // value will be created. final String donorSource = "#version 300 es\n" + "void main() {\n" + " int x = 0;\n" + " {\n" + " int A[1];\n" + " A[x] = 42;\n" + " {\n" + " int B[1];\n" + " B[x] = 42;\n" + " {\n" + " int C[1];\n" + " C[x] = 42;\n" + " }\n" + " }\n" + " }\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(donorSource) .setUniformsInfo("{}"), new File(donors, "donor.json") ); } { final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; fileOps.writeShaderJobFileFromImageJob( new ImageJob() .setFragmentSource(referenceSource) .setUniformsInfo("{}"), referenceFile ); } int noCodeDonatedCount = 0; // Try the following a few times, so that there is a good chance of triggering the issue // this test was used to catch, should it return: for (int seed = 0; seed < 15; seed++) { final ShaderJob referenceShaderJob = fileOps.readShaderJobFile(referenceFile); // Do live code donation. DonateLiveCodeTransformation transformation = new DonateLiveCodeTransformation(IRandom::nextBoolean, donors, GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); assert referenceShaderJob.getFragmentShader().isPresent(); boolean result = transformation.apply( referenceShaderJob.getFragmentShader().get(), TransformationProbabilities.onlyLiveCodeAlwaysSubstitute(), new RandomWrapper(seed), GenerationParams.normal(ShaderKind.FRAGMENT, false, true) ); if (!result) { ++noCodeDonatedCount; continue; } // An array access injected into the shader must either be (1) already in bounds, or // (2) made in bounds. Only in the former case can the array index be a variable identifier // expression, and in that case the expression cannot realistically be statically in bounds // if the initializer for that expression is under a _GLF_FUZZED macro. (There is a tiny // chance that the fuzzed expression might statically evaluate to 0, but currently a // _GLF_FUZZED macro will be treated as not statically in bounds, so the access would be // made in bounds in that case.) // // The following thus checks that if an array is indexed directly by a variable reference, // the initializer for that variable is not a function call expression. new ScopeTrackingVisitor() { @Override public void visitArrayIndexExpr(ArrayIndexExpr arrayIndexExpr) { super.visitArrayIndexExpr(arrayIndexExpr); if (arrayIndexExpr.getIndex() instanceof VariableIdentifierExpr) { final ScopeEntry scopeEntry = getCurrentScope().lookupScopeEntry( ((VariableIdentifierExpr) arrayIndexExpr.getIndex()).getName()); assertTrue(scopeEntry.hasVariableDeclInfo()); assertNotNull(scopeEntry.getVariableDeclInfo().getInitializer()); assertFalse((scopeEntry.getVariableDeclInfo().getInitializer()) .getExpr() instanceof FunctionCallExpr); } } }.visit(referenceShaderJob.getFragmentShader().get()); } // The above code tests donation of live code, but there is still a chance that no code will // be donated. We assert that this happens < 10 times to ensure that we get some test // coverage, but this could fail due to bad luck. Assert.assertTrue( "Donation failure count should be < 10, " + noCodeDonatedCount, noCodeDonatedCount < 10 ); } private void checkLiveCodeDonationRepeatedly(String donorSource, String referenceSource, Predicate<TranslationUnit> check, int numIterations) throws Exception { final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final File donors = testFolder.newFolder("donors"); final File referenceFile = testFolder.newFile("reference.json"); fileOps.writeShaderJobFile( new GlslShaderJob( Optional.empty(), new PipelineInfo(), ParseHelper.parse(donorSource)), new File(donors, "donor.json") ); fileOps.writeShaderJobFile( new GlslShaderJob( Optional.empty(), new PipelineInfo(), ParseHelper.parse(referenceSource)), referenceFile ); int noCodeDonatedCount = 0; // Try the following a few times, so that there is a good chance of triggering the issue // this test was used to catch, should it return: for (int seed = 0; seed < numIterations; seed++) { final ShaderJob referenceShaderJob = fileOps.readShaderJobFile(referenceFile); // Do live code donation. final DonateLiveCodeTransformation transformation = new DonateLiveCodeTransformation(IRandom::nextBoolean, donors, GenerationParams.normal(ShaderKind.FRAGMENT, false, true), false); assert referenceShaderJob.getFragmentShader().isPresent(); final boolean result = transformation.apply( referenceShaderJob.getFragmentShader().get(), TransformationProbabilities.onlyLiveCodeAlwaysSubstitute(), new RandomWrapper(seed), GenerationParams.normal(ShaderKind.FRAGMENT, false, true) ); // Check that the resulting shader typechecks. new Typer(referenceShaderJob.getFragmentShader().get()); // Check that the user-provided predicate holds. assertTrue(check.test(referenceShaderJob.getFragmentShader().get())); if (result) { final File tempFile = testFolder.newFile("shader" + seed + ".json"); fileOps.writeShaderJobFile(referenceShaderJob, tempFile); // This will fail if the shader job turns out to be invalid. fileOps.areShadersValid(tempFile, true); } else { ++noCodeDonatedCount; } } // The above code tests donation of live code, but there is still a chance that no code will // be donated. We assert that this doesn't happen too often to ensure that we get some test // coverage, but this could fail due to bad luck. Assert.assertTrue( "Donation failure count is too high: " + noCodeDonatedCount + " out of " + numIterations, noCodeDonatedCount < numIterations * 0.6 ); } @Test public void testInAndOutParametersDonatedOk() throws Exception { // This checks that donation of code that uses 'in' and 'out' parameters of functions works. // This donor is designed to have a high chance of leading to an in, out or inout parameter // being used by a donated statement, making it a free variable for which a local variable // will need to be declared. final String donorSource = "#version 300 es\n" + "void foo(in int a, out int b, inout int c) {\n" + " {\n" + " {\n" + " {\n" + " b = a;\n" + " c = c + a;\n" + " }\n" + " }\n" + " }\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } @Test public void testDonationOfArrayThatUsesSizeExpr() throws Exception { // This checks that donation of code that uses an array with a non-trivial constant expression // as its size. // This donor is designed to have a high chance of leading to the write to array A, but not // the declaration of A, being donated. The array will then need to have explicit size 7, // not size M + N. final String donorSource = "#version 300 es\n" + "void foo(in int a, out int b, inout int c) {\n" + " {\n" + " const int N = 3;\n" + " const int M = 4;\n" + " int A[M + N];\n" + " {\n" + " {\n" + " A[0] = 12;\n" + " }\n" + " }\n" + " }\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } @Test public void testDonationOfFreeTypeConstructors() throws Exception { // This checks that donation of code that uses type constructors leads to valid shaders. final String donorSource = "#version 300 es\n" + "precision highp float;\n" + "void foo(in int a, out int b, inout int c) {\n" + " {\n" + " mat2x2 m = mat2x2(1.0);\n" + " vec2 v = vec2(1.0);\n" + " ivec3 iv = ivec3(3);\n" + " }\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } @Test public void testDonationOfCodeThatUsesGlobalStruct() throws Exception { // This checks that donation of code that uses a global struct variable declared with its // struct declaration works properly. final String donorSource = "#version 300 es\n" + "struct S {\n" + " int x;" + "} s;\n" + "void foo() {\n" + " {\n" + " int a;\n" + " a = s.x;\n" + " }\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } @Test public void testNoDonationOfCodeThatUsesLocalStruct() throws Exception { // This checks that functions that declare local structs are not used for donation. final String donorSource = "#version 300 es\n" + "void foo(struct S { int a; } p) {\n" + " p.a = 2;\n" + "}\n" + "void bar(struct { int a; } p) {\n" + " p.a = 2;\n" + "}\n" + "void baz() {\n" + " struct T {\n" + " int a; int b;\n" + " };\n" + " T myT;\n" + " myT.a = myT.b;\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void main() {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } @Test public void testDoNotUseConstParameterInConstExpression() throws Exception { // This checks that when fuzzing initializers, a const parameter is not used for a // const variable. // This donor makes heavy use of non-global structs. final String donorSource = "#version 300 es\n" + "void foo() {\n" + " const int a = 10;\n" + " {\n" + " int b;\n" + " b = a;\n" + " }\n" + "}\n"; final String referenceSource = "#version 300 es\n" + "void foo(const int x) {\n" + "}\n"; checkLiveCodeDonationRepeatedly(donorSource, referenceSource, item -> true, 15); } }
apache/geode
35,061
geode-lucene/src/integrationTest/java/org/apache/geode/cache/lucene/internal/cli/LuceneIndexCommandsIntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.lucene.internal.cli; import static org.apache.geode.cache.Region.SEPARATOR; import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.INDEX_NAME; import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.REGION_NAME; import static org.apache.geode.test.awaitility.GeodeAwaitility.await; import static org.apache.geode.test.dunit.Assert.assertArrayEquals; import static org.apache.geode.test.dunit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import junitparams.Parameters; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.lucene.LuceneIndex; import org.apache.geode.cache.lucene.LuceneQuery; import org.apache.geode.cache.lucene.LuceneQueryException; import org.apache.geode.cache.lucene.LuceneService; import org.apache.geode.cache.lucene.LuceneServiceProvider; import org.apache.geode.cache.lucene.internal.LuceneIndexCreationProfile; import org.apache.geode.cache.lucene.internal.LuceneIndexImpl; import org.apache.geode.cache.lucene.internal.LuceneServiceImpl; import org.apache.geode.cache.lucene.internal.repository.serializer.PrimitiveSerializer; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.management.cli.Result.Status; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.util.CommandStringBuilder; import org.apache.geode.management.internal.i18n.CliStrings; import org.apache.geode.test.junit.assertions.CommandResultAssert; import org.apache.geode.test.junit.categories.LuceneTest; import org.apache.geode.test.junit.rules.GfshCommandRule; import org.apache.geode.test.junit.rules.ServerStarterRule; import org.apache.geode.test.junit.rules.serializable.SerializableTestName; import org.apache.geode.test.junit.runners.GeodeParamsRunner; @Category(LuceneTest.class) @RunWith(GeodeParamsRunner.class) @SuppressWarnings("serial") public class LuceneIndexCommandsIntegrationTest { @Rule public transient GfshCommandRule gfsh = new GfshCommandRule(); @Rule public SerializableTestName testName = new SerializableTestName(); @Rule public ServerStarterRule server = new ServerStarterRule(); @Before public void before() throws Exception { server.withProperty(ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.cache.lucene.internal.cli.LuceneIndexCommandsWithReindexAllowedIntegrationTest" + ";org.apache.geode.cache.lucene.internal.cli.LuceneIndexCommandsIntegrationTest*" + ";org.apache.geode.test.**") .withJMXManager().startServer(); gfsh.connectAndVerify(server.getJmxPort(), GfshCommandRule.PortType.jmxManager); } @Test public void listIndexShouldReturnExistingIndexWithStats() throws Exception { createIndex(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX); csb.addOption(LuceneCliStrings.LUCENE_LIST_INDEX__STATS, "true"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .tableHasColumnWithExactValuesInAnyOrder("Documents", "0") .tableHasColumnWithExactValuesInAnyOrder("Index Name", "index"); } @Test public void listIndexShouldReturnExistingIndexWithoutStats() throws Exception { createIndex(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput(INDEX_NAME) .doesNotContainOutput("Documents"); } @Test public void listIndexWhenNoExistingIndexShouldReturnNoIndex() throws Exception { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX); gfsh.executeAndAssertThat(csb.toString()).containsOutput("No lucene indexes found"); } @Test public void listIndexShouldReturnCorrectStatus() throws Exception { createIndexWithoutRegion(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX); csb.addOption(LuceneCliStrings.LUCENE_LIST_INDEX__STATS, "true"); gfsh.executeAndAssertThat(csb.toString()) .tableHasColumnWithExactValuesInAnyOrder("Status", "NOT_INITIALIZED") .tableHasColumnWithExactValuesInAnyOrder("Index Name", INDEX_NAME); } @Test public void listIndexWithStatsShouldReturnCorrectStats() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("field1:value1", "field2:value2", "field3:value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); putEntries(entries, 2); queryAndVerify("field1:value1", "field1"); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_LIST_INDEX); csb.addOption(LuceneCliStrings.LUCENE_LIST_INDEX__STATS, "true"); CommandResult result = gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .tableHasColumnOnlyWithValues("Index Name", INDEX_NAME) .tableHasColumnOnlyWithValues("Status", "INITIALIZED") .tableHasColumnOnlyWithValues("Region Path", SEPARATOR + "region") .tableHasColumnOnlyWithValues("Query Executions", "1") .getCommandResult(); // the document count could be greater than 2 List<String> documents = result.getResultData().getTableSections().get(0).getValuesInColumn("Documents"); assertThat(documents).hasSize(1); assertThat(Integer.parseInt(documents.get(0))).isGreaterThanOrEqualTo(2); } @Test public void createIndexShouldCreateANewIndex() { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); createRegion(); LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME); assertArrayEquals(new String[] {"field1", "field2", "field3"}, index.getFieldNames()); } @Test public void createIndexWithAnalyzersShouldCreateANewIndex() { List<String> analyzerNames = new ArrayList<>(); analyzerNames.add(StandardAnalyzer.class.getCanonicalName()); analyzerNames.add(KeywordAnalyzer.class.getCanonicalName()); analyzerNames.add(StandardAnalyzer.class.getCanonicalName()); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, String.join(",", analyzerNames)); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); createRegion(); LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME); final Map<String, Analyzer> fieldAnalyzers = index.getFieldAnalyzers(); assertEquals(StandardAnalyzer.class, fieldAnalyzers.get("field1").getClass()); assertEquals(KeywordAnalyzer.class, fieldAnalyzers.get("field2").getClass()); assertEquals(StandardAnalyzer.class, fieldAnalyzers.get("field3").getClass()); } @Test public void createIndexWithALuceneSerializerShouldCreateANewIndex() { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__SERIALIZER, PrimitiveSerializer.class.getCanonicalName()); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); createRegion(); LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME); assertThat(index.getLuceneSerializer()).isInstanceOf(PrimitiveSerializer.class); } @Test public void createIndexShouldNotAcceptBadIndexOrRegionNames() { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, "'__'"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput( "Region names may only be alphanumeric, must not begin with double-underscores, but can contain hyphens, underscores, or forward slashes:"); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, "' @@@*%'"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput( "Region names may only be alphanumeric, must not begin with double-underscores, but can contain hyphens, underscores, or forward slashes:"); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "'__'"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput( "Index names may only be alphanumeric, must not begin with double-underscores, but can contain hyphens or underscores:"); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "' @@@*%'"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput( "Index names may only be alphanumeric, must not begin with double-underscores, but can contain hyphens or underscores:"); } @Test public void createIndexShouldTrimAnalyzerNames() { List<String> analyzerNames = new ArrayList<>(); analyzerNames.add(StandardAnalyzer.class.getCanonicalName()); analyzerNames.add(KeywordAnalyzer.class.getCanonicalName()); analyzerNames.add(StandardAnalyzer.class.getCanonicalName()); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, "\"org.apache.lucene.analysis.standard.StandardAnalyzer, org.apache.lucene.analysis.core.KeywordAnalyzer, org.apache.lucene.analysis.standard.StandardAnalyzer\""); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); createRegion(); LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); final LuceneIndex index = luceneService.getIndex(INDEX_NAME, REGION_NAME); final Map<String, Analyzer> fieldAnalyzers = index.getFieldAnalyzers(); assertEquals(StandardAnalyzer.class, fieldAnalyzers.get("field1").getClass()); assertEquals(KeywordAnalyzer.class, fieldAnalyzers.get("field2").getClass()); assertEquals(StandardAnalyzer.class, fieldAnalyzers.get("field3").getClass()); } @Test public void createIndexWithoutRegionShouldReturnCorrectResults() throws Exception { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess(); LuceneServiceImpl luceneService = (LuceneServiceImpl) LuceneServiceProvider.get(server.getCache()); final ArrayList<LuceneIndexCreationProfile> profiles = new ArrayList<>(luceneService.getAllDefinedIndexes()); assertEquals(1, profiles.size()); assertEquals(INDEX_NAME, profiles.get(0).getIndexName()); } @Test public void createIndexWithWhitespaceOrDefaultKeywordAnalyzerShouldUseStandardAnalyzer() { // Test whitespace analyzer name String analyzerList = StandardAnalyzer.class.getCanonicalName() + ", ," + KeywordAnalyzer.class.getCanonicalName(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "space"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, "'" + analyzerList + "'"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); // Test empty analyzer name analyzerList = StandardAnalyzer.class.getCanonicalName() + ",," + KeywordAnalyzer.class.getCanonicalName(); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "empty"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, analyzerList); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); // Test keyword analyzer name analyzerList = StandardAnalyzer.class.getCanonicalName() + ",DEFAULT," + KeywordAnalyzer.class.getCanonicalName(); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "keyword"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__ANALYZER, analyzerList); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("Successfully created lucene index"); LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); createRegion(); final LuceneIndex spaceIndex = luceneService.getIndex("space", REGION_NAME); final Map<String, Analyzer> spaceFieldAnalyzers = spaceIndex.getFieldAnalyzers(); final LuceneIndex emptyIndex = luceneService.getIndex("empty", REGION_NAME); final Map<String, Analyzer> emptyFieldAnalyzers2 = emptyIndex.getFieldAnalyzers(); final LuceneIndex keywordIndex = luceneService.getIndex("keyword", REGION_NAME); final Map<String, Analyzer> keywordFieldAnalyzers = keywordIndex.getFieldAnalyzers(); // Test whitespace analyzers assertEquals(StandardAnalyzer.class.getCanonicalName(), spaceFieldAnalyzers.get("field1").getClass().getCanonicalName()); assertEquals(StandardAnalyzer.class.getCanonicalName(), spaceFieldAnalyzers.get("field2").getClass().getCanonicalName()); assertEquals(KeywordAnalyzer.class.getCanonicalName(), spaceFieldAnalyzers.get("field3").getClass().getCanonicalName()); // Test empty analyzers assertEquals(StandardAnalyzer.class.getCanonicalName(), emptyFieldAnalyzers2.get("field1").getClass().getCanonicalName()); assertEquals(StandardAnalyzer.class.getCanonicalName(), emptyFieldAnalyzers2.get("field2").getClass().getCanonicalName()); assertEquals(KeywordAnalyzer.class.getCanonicalName(), emptyFieldAnalyzers2.get("field3").getClass().getCanonicalName()); // Test keyword analyzers assertEquals(StandardAnalyzer.class.getCanonicalName(), keywordFieldAnalyzers.get("field1").getClass().getCanonicalName()); assertEquals(StandardAnalyzer.class.getCanonicalName(), keywordFieldAnalyzers.get("field2").getClass().getCanonicalName()); assertEquals(KeywordAnalyzer.class.getCanonicalName(), keywordFieldAnalyzers.get("field3").getClass().getCanonicalName()); } @Test public void describeIndexShouldReturnExistingIndex() throws Exception { createIndex(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess().containsOutput(INDEX_NAME); } @Test public void describeIndexShouldShowSerializer() throws Exception { CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_CREATE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__FIELD, "field1,field2,field3"); csb.addOption(LuceneCliStrings.LUCENE_CREATE_INDEX__SERIALIZER, PrimitiveSerializer.class.getCanonicalName()); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess(); createRegion(); csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput(PrimitiveSerializer.class.getSimpleName()); } @Test public void describeIndexShouldNotReturnResultWhenIndexNotFound() throws Exception { createIndex(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "notAnIndex"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput("No lucene indexes found"); } @Test public void describeIndexWithoutRegionShouldReturnErrorMessage() throws Exception { createIndexWithoutRegion(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_DESCRIBE_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, "notAnIndex"); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); gfsh.executeAndAssertThat(csb.toString()).statusIsError().containsOutput(REGION_NAME); } @Test public void searchShouldReturnCorrectResults() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("value1 ", "value2", "value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); entries.put("C", new TestObject("value1", "QWE", "RTY")); entries.put("D", new TestObject("ABC", "EFG", "HIJ")); entries.put("E", new TestObject("value1", "ABC", "EFG")); entries.put("F", new TestObject("ABC", "EFG", "HIJ")); entries.put("G", new TestObject(" value1", "JKR", "POW")); entries.put("H", new TestObject("ABC", "EFG", "H2J")); putEntries(entries, 8); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "field1:value1"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field1"); gfsh.executeAndAssertThat(csb.toString()).tableHasColumnWithExactValuesInAnyOrder("key", "E", "A", "G", "C"); } @Test public void searchShouldReturnResultsInCorrectOrderOfScore() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("jon ", "value2", "value3")); entries.put("B", new TestObject("don", "EFG", "HIJ")); entries.put("C", new TestObject("eon", "QWE", "RTY")); entries.put("D", new TestObject("kion", "QWE", "RTY")); entries.put("E", new TestObject("ryan", "QWE", "RTY")); putEntries(entries, 5); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "field1:jon~"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field1"); CommandResultAssert assertion = gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess(); try { assertion.hasTableSection().hasColumn("key").containsExactly("A", "B", "C", "D"); } catch (AssertionError e) { // Since B and C have the same score, we can expect them to appear in either order assertion.hasTableSection().hasColumn("key").containsExactly("A", "C", "B", "D"); } } @Test public void searchShouldReturnNoResults() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("value1 ", "value2", "value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); entries.put("C", new TestObject("value1", "QWE", "RTY")); entries.put("D", new TestObject("ABC", "EFG", "HIJ")); entries.put("E", new TestObject(":value1", "ABC", "EFG")); entries.put("F", new TestObject("ABC", "EFG", "HIJ")); entries.put("G", new TestObject(" value1", "JKR", "POW")); entries.put("H", new TestObject("ABC", "EFG", "H2J")); putEntries(entries, 8); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "NotAnExistingValue"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field1"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .containsOutput(LuceneCliStrings.LUCENE_SEARCH_INDEX__NO_RESULTS_MESSAGE); } @Test public void searchWithLimitShouldReturnCorrectResults() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("value1 ", "value2", "value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); entries.put("C", new TestObject("value1", "QWE", "RTY")); entries.put("D", new TestObject("ABC", "EFG", "HIJ")); entries.put("E", new TestObject("value1", "ABC", "EFG")); entries.put("F", new TestObject("ABC", "EFG", "HIJ")); entries.put("G", new TestObject(" value1", "JKR", "POW")); entries.put("H", new TestObject("ABC", "EFG", "H2J")); putEntries(entries, 8); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "field1:value1"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field1"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__LIMIT, "2"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .tableHasColumnWithExactValuesInAnyOrder("key", "A", "G"); } @Test public void searchWithoutFieldNameShouldReturnCorrectResults() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("value1 ", "value2", "value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); entries.put("C", new TestObject("value1", "QWE", "RTY")); entries.put("D", new TestObject("ABC", "EFG", "HIJ")); entries.put("E", new TestObject("value1", "ABC", "EFG")); entries.put("F", new TestObject("ABC", "EFG", "HIJ")); entries.put("G", new TestObject("value1", "JKR", "POW")); entries.put("H", new TestObject("ABC", "EFG", "H2J")); putEntries(entries, 8); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "QWE"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field2"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .tableHasColumnWithExactValuesInAnyOrder("key", "C"); } @Test public void searchOnIndexWithoutRegionShouldReturnError() throws Exception { createIndexWithoutRegion(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "EFG"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field2"); gfsh.executeAndAssertThat(csb.toString()).statusIsError() .containsOutput(getRegionNotFoundErrorMessage(SEPARATOR + "region")); } @Test public void searchWithoutIndexShouldReturnError() throws Exception { createRegion(); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "EFG"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field2"); String commandString = csb.toString(); writeToLog("Command String :\n ", commandString); CommandResult commandResult = gfsh.executeCommand(commandString); String resultAsString = gfsh.getGfshOutput(); writeToLog("Result String :\n ", resultAsString); assertEquals(Status.ERROR, commandResult.getStatus()); assertEquals("Unexpected CommandResult string :" + resultAsString, true, resultAsString.contains("Index " + INDEX_NAME + " not found")); } @Test public void searchIndexShouldReturnCorrectKeys() throws Exception { createIndex(); Map<String, TestObject> entries = new HashMap<>(); entries.put("A", new TestObject("value1 ", "value2", "value3")); entries.put("B", new TestObject("ABC", "EFG", "HIJ")); entries.put("C", new TestObject("value1", "QWE", "RTY")); entries.put("D", new TestObject("ABC", "EFG", "HIJ")); entries.put("E", new TestObject("value1", "ABC", "EFG")); entries.put("F", new TestObject("ABC", "EFG", "HIJ")); entries.put("G", new TestObject("value1", "JKR", "POW")); entries.put("H", new TestObject("ABC", "EFG", "H2J")); putEntries(entries, 8); CommandStringBuilder csb = new CommandStringBuilder(LuceneCliStrings.LUCENE_SEARCH_INDEX); csb.addOption(LuceneCliStrings.LUCENE__INDEX_NAME, INDEX_NAME); csb.addOption(LuceneCliStrings.LUCENE__REGION_PATH, REGION_NAME); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__QUERY_STRING, "value1"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__DEFAULT_FIELD, "field1"); csb.addOption(LuceneCliStrings.LUCENE_SEARCH_INDEX__KEYSONLY, "true"); gfsh.executeAndAssertThat(csb.toString()).statusIsSuccess() .tableHasColumnWithExactValuesInAnyOrder("key", "C", "G", "E", "A"); } @Test @Parameters({"true", "false"}) public void testDestroySingleIndex(boolean createRegion) throws Exception { if (createRegion) { createIndex(); } else { createIndexWithoutRegion(); } String expectedStatus = CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEX_0_FROM_REGION_1, "index", SEPARATOR + "region"); gfsh.executeAndAssertThat("destroy lucene index --name=index --region=region").statusIsSuccess() .containsOutput(expectedStatus); } @Test @Parameters({"true", "false"}) public void testDestroyAllIndexes(boolean createRegion) throws Exception { if (createRegion) { createIndex(); } else { createIndexWithoutRegion(); } // Verify destroy all indexes is successful String expectedOutput = CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__SUCCESSFULLY_DESTROYED_INDEXES_FROM_REGION_0, new Object[] {SEPARATOR + "region"}); gfsh.executeAndAssertThat("destroy lucene index --region=region").statusIsSuccess() .containsOutput(expectedOutput); // Verify destroy all indexes again reports no indexes exist expectedOutput = String.format("No Lucene indexes were found in region %s", SEPARATOR + "region"); gfsh.executeAndAssertThat("destroy lucene index --region=region").statusIsSuccess() .containsOutput(expectedOutput); } @Test public void testDestroyNonExistentSingleIndex() throws Exception { createRegion(); String expectedStatus = String.format("Lucene index %s was not found in region %s", INDEX_NAME, SEPARATOR + REGION_NAME); gfsh.executeAndAssertThat("destroy lucene index --name=index --region=region").statusIsSuccess() .containsOutput(expectedStatus); } @Test public void testDestroyNonExistentIndexes() throws Exception { createRegion(); String expectedOutput = String.format("No Lucene indexes were found in region %s", SEPARATOR + "region"); gfsh.executeAndAssertThat("destroy lucene index --region=region").statusIsSuccess() .containsOutput(expectedOutput); } protected void createRegion() { server.getCache().createRegionFactory(RegionShortcut.PARTITION).create(REGION_NAME); } private void createIndex() { LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); Map<String, Analyzer> fieldAnalyzers = new HashMap(); fieldAnalyzers.put("field1", new StandardAnalyzer()); fieldAnalyzers.put("field2", new KeywordAnalyzer()); fieldAnalyzers.put("field3", null); luceneService.createIndexFactory().setFields(fieldAnalyzers).create(INDEX_NAME, REGION_NAME); createRegion(); } private void createIndexWithoutRegion() { LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); Map<String, Analyzer> fieldAnalyzers = new HashMap(); fieldAnalyzers.put("field1", new StandardAnalyzer()); fieldAnalyzers.put("field2", new KeywordAnalyzer()); fieldAnalyzers.put("field3", null); luceneService.createIndexFactory().setFields(fieldAnalyzers).create(INDEX_NAME, REGION_NAME); } private void writeToLog(String text, String resultAsString) { System.out.println(text + ": " + testName.getMethodName() + " : "); System.out.println(text + ":" + resultAsString); } private void putEntries(Map<String, TestObject> entries, int countOfDocuments) throws InterruptedException { LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); Region region = server.getCache().getRegion(REGION_NAME); region.putAll(entries); luceneService.waitUntilFlushed(INDEX_NAME, REGION_NAME, 60000, TimeUnit.MILLISECONDS); LuceneIndexImpl index = (LuceneIndexImpl) luceneService.getIndex(INDEX_NAME, REGION_NAME); await().until( () -> index.getIndexStats().getDocuments() >= countOfDocuments); } private void queryAndVerify(String queryString, String defaultField) throws LuceneQueryException { LuceneService luceneService = LuceneServiceProvider.get(server.getCache()); final LuceneQuery<String, TestObject> query = luceneService.createLuceneQueryFactory() .create(INDEX_NAME, REGION_NAME, queryString, defaultField); assertEquals(Collections.singletonList("A"), query.findKeys()); } private String getRegionNotFoundErrorMessage(String regionPath) { return CliStrings.format( LuceneCliStrings.LUCENE_DESTROY_INDEX__MSG__COULDNOT_FIND_MEMBERS_FOR_REGION_0, new Object[] {regionPath}); } protected static class TestObject implements Serializable { private final String field1; private final String field2; private final String field3; protected TestObject(String value1, String value2, String value3) { field1 = value1; field2 = value2; field3 = value3; } public String toString() { return "field1=" + field1 + " field2=" + field2 + " field3=" + field3; } } }
googleapis/google-cloud-java
35,335
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/ListEntriesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataplex/v1/catalog.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * List Entries response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEntriesResponse} */ public final class ListEntriesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.ListEntriesResponse) ListEntriesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListEntriesResponse.newBuilder() to construct. private ListEntriesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEntriesResponse() { entries_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEntriesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_ListEntriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_ListEntriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEntriesResponse.class, com.google.cloud.dataplex.v1.ListEntriesResponse.Builder.class); } public static final int ENTRIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dataplex.v1.Entry> entries_; /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dataplex.v1.Entry> getEntriesList() { return entries_; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dataplex.v1.EntryOrBuilder> getEntriesOrBuilderList() { return entries_; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ @java.lang.Override public int getEntriesCount() { return entries_.size(); } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.Entry getEntries(int index) { return entries_.get(index); } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.EntryOrBuilder getEntriesOrBuilder(int index) { return entries_.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 < entries_.size(); i++) { output.writeMessage(1, entries_.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 < entries_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entries_.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.dataplex.v1.ListEntriesResponse)) { return super.equals(obj); } com.google.cloud.dataplex.v1.ListEntriesResponse other = (com.google.cloud.dataplex.v1.ListEntriesResponse) obj; if (!getEntriesList().equals(other.getEntriesList())) 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 (getEntriesCount() > 0) { hash = (37 * hash) + ENTRIES_FIELD_NUMBER; hash = (53 * hash) + getEntriesList().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.dataplex.v1.ListEntriesResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntriesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataplex.v1.ListEntriesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * List Entries response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEntriesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.ListEntriesResponse) com.google.cloud.dataplex.v1.ListEntriesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_ListEntriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_ListEntriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEntriesResponse.class, com.google.cloud.dataplex.v1.ListEntriesResponse.Builder.class); } // Construct using com.google.cloud.dataplex.v1.ListEntriesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (entriesBuilder_ == null) { entries_ = java.util.Collections.emptyList(); } else { entries_ = null; entriesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_ListEntriesResponse_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntriesResponse getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.ListEntriesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntriesResponse build() { com.google.cloud.dataplex.v1.ListEntriesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntriesResponse buildPartial() { com.google.cloud.dataplex.v1.ListEntriesResponse result = new com.google.cloud.dataplex.v1.ListEntriesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dataplex.v1.ListEntriesResponse result) { if (entriesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { entries_ = java.util.Collections.unmodifiableList(entries_); bitField0_ = (bitField0_ & ~0x00000001); } result.entries_ = entries_; } else { result.entries_ = entriesBuilder_.build(); } } private void buildPartial0(com.google.cloud.dataplex.v1.ListEntriesResponse 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.dataplex.v1.ListEntriesResponse) { return mergeFrom((com.google.cloud.dataplex.v1.ListEntriesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.ListEntriesResponse other) { if (other == com.google.cloud.dataplex.v1.ListEntriesResponse.getDefaultInstance()) return this; if (entriesBuilder_ == null) { if (!other.entries_.isEmpty()) { if (entries_.isEmpty()) { entries_ = other.entries_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEntriesIsMutable(); entries_.addAll(other.entries_); } onChanged(); } } else { if (!other.entries_.isEmpty()) { if (entriesBuilder_.isEmpty()) { entriesBuilder_.dispose(); entriesBuilder_ = null; entries_ = other.entries_; bitField0_ = (bitField0_ & ~0x00000001); entriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntriesFieldBuilder() : null; } else { entriesBuilder_.addAllMessages(other.entries_); } } } 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.dataplex.v1.Entry m = input.readMessage( com.google.cloud.dataplex.v1.Entry.parser(), extensionRegistry); if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.add(m); } else { entriesBuilder_.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.dataplex.v1.Entry> entries_ = java.util.Collections.emptyList(); private void ensureEntriesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { entries_ = new java.util.ArrayList<com.google.cloud.dataplex.v1.Entry>(entries_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entry, com.google.cloud.dataplex.v1.Entry.Builder, com.google.cloud.dataplex.v1.EntryOrBuilder> entriesBuilder_; /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Entry> getEntriesList() { if (entriesBuilder_ == null) { return java.util.Collections.unmodifiableList(entries_); } else { return entriesBuilder_.getMessageList(); } } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public int getEntriesCount() { if (entriesBuilder_ == null) { return entries_.size(); } else { return entriesBuilder_.getCount(); } } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public com.google.cloud.dataplex.v1.Entry getEntries(int index) { if (entriesBuilder_ == null) { return entries_.get(index); } else { return entriesBuilder_.getMessage(index); } } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder setEntries(int index, com.google.cloud.dataplex.v1.Entry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.set(index, value); onChanged(); } else { entriesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder setEntries( int index, com.google.cloud.dataplex.v1.Entry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.set(index, builderForValue.build()); onChanged(); } else { entriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder addEntries(com.google.cloud.dataplex.v1.Entry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.add(value); onChanged(); } else { entriesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder addEntries(int index, com.google.cloud.dataplex.v1.Entry value) { if (entriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntriesIsMutable(); entries_.add(index, value); onChanged(); } else { entriesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder addEntries(com.google.cloud.dataplex.v1.Entry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.add(builderForValue.build()); onChanged(); } else { entriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder addEntries( int index, com.google.cloud.dataplex.v1.Entry.Builder builderForValue) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.add(index, builderForValue.build()); onChanged(); } else { entriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder addAllEntries( java.lang.Iterable<? extends com.google.cloud.dataplex.v1.Entry> values) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entries_); onChanged(); } else { entriesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder clearEntries() { if (entriesBuilder_ == null) { entries_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { entriesBuilder_.clear(); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public Builder removeEntries(int index) { if (entriesBuilder_ == null) { ensureEntriesIsMutable(); entries_.remove(index); onChanged(); } else { entriesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public com.google.cloud.dataplex.v1.Entry.Builder getEntriesBuilder(int index) { return getEntriesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public com.google.cloud.dataplex.v1.EntryOrBuilder getEntriesOrBuilder(int index) { if (entriesBuilder_ == null) { return entries_.get(index); } else { return entriesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public java.util.List<? extends com.google.cloud.dataplex.v1.EntryOrBuilder> getEntriesOrBuilderList() { if (entriesBuilder_ != null) { return entriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entries_); } } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public com.google.cloud.dataplex.v1.Entry.Builder addEntriesBuilder() { return getEntriesFieldBuilder() .addBuilder(com.google.cloud.dataplex.v1.Entry.getDefaultInstance()); } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public com.google.cloud.dataplex.v1.Entry.Builder addEntriesBuilder(int index) { return getEntriesFieldBuilder() .addBuilder(index, com.google.cloud.dataplex.v1.Entry.getDefaultInstance()); } /** * * * <pre> * The list of entries under the given parent location. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entry entries = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Entry.Builder> getEntriesBuilderList() { return getEntriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entry, com.google.cloud.dataplex.v1.Entry.Builder, com.google.cloud.dataplex.v1.EntryOrBuilder> getEntriesFieldBuilder() { if (entriesBuilder_ == null) { entriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entry, com.google.cloud.dataplex.v1.Entry.Builder, com.google.cloud.dataplex.v1.EntryOrBuilder>( entries_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); entries_ = null; } return entriesBuilder_; } 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.dataplex.v1.ListEntriesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.ListEntriesResponse) private static final com.google.cloud.dataplex.v1.ListEntriesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.ListEntriesResponse(); } public static com.google.cloud.dataplex.v1.ListEntriesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEntriesResponse> PARSER = new com.google.protobuf.AbstractParser<ListEntriesResponse>() { @java.lang.Override public ListEntriesResponse 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<ListEntriesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEntriesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntriesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,356
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ReceiveEventsResponse.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/streaming_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Response message for the ReceiveEvents. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ReceiveEventsResponse} */ public final class ReceiveEventsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ReceiveEventsResponse) ReceiveEventsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ReceiveEventsResponse.newBuilder() to construct. private ReceiveEventsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ReceiveEventsResponse() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ReceiveEventsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamingServiceProto .internal_static_google_cloud_visionai_v1_ReceiveEventsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamingServiceProto .internal_static_google_cloud_visionai_v1_ReceiveEventsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ReceiveEventsResponse.class, com.google.cloud.visionai.v1.ReceiveEventsResponse.Builder.class); } private int responseCase_ = 0; @SuppressWarnings("serial") private java.lang.Object response_; public enum ResponseCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { EVENT_UPDATE(1), CONTROL(2), RESPONSE_NOT_SET(0); private final int value; private ResponseCase(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 ResponseCase valueOf(int value) { return forNumber(value); } public static ResponseCase forNumber(int value) { switch (value) { case 1: return EVENT_UPDATE; case 2: return CONTROL; case 0: return RESPONSE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ResponseCase getResponseCase() { return ResponseCase.forNumber(responseCase_); } public static final int EVENT_UPDATE_FIELD_NUMBER = 1; /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> * * @return Whether the eventUpdate field is set. */ @java.lang.Override public boolean hasEventUpdate() { return responseCase_ == 1; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> * * @return The eventUpdate. */ @java.lang.Override public com.google.cloud.visionai.v1.EventUpdate getEventUpdate() { if (responseCase_ == 1) { return (com.google.cloud.visionai.v1.EventUpdate) response_; } return com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.EventUpdateOrBuilder getEventUpdateOrBuilder() { if (responseCase_ == 1) { return (com.google.cloud.visionai.v1.EventUpdate) response_; } return com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } public static final int CONTROL_FIELD_NUMBER = 2; /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> * * @return Whether the control field is set. */ @java.lang.Override public boolean hasControl() { return responseCase_ == 2; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> * * @return The control. */ @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsControlResponse getControl() { if (responseCase_ == 2) { return (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_; } return com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance(); } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsControlResponseOrBuilder getControlOrBuilder() { if (responseCase_ == 2) { return (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_; } return com.google.cloud.visionai.v1.ReceiveEventsControlResponse.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 (responseCase_ == 1) { output.writeMessage(1, (com.google.cloud.visionai.v1.EventUpdate) response_); } if (responseCase_ == 2) { output.writeMessage(2, (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (responseCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.cloud.visionai.v1.EventUpdate) response_); } if (responseCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_); } 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.ReceiveEventsResponse)) { return super.equals(obj); } com.google.cloud.visionai.v1.ReceiveEventsResponse other = (com.google.cloud.visionai.v1.ReceiveEventsResponse) obj; if (!getResponseCase().equals(other.getResponseCase())) return false; switch (responseCase_) { case 1: if (!getEventUpdate().equals(other.getEventUpdate())) return false; break; case 2: if (!getControl().equals(other.getControl())) 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 (responseCase_) { case 1: hash = (37 * hash) + EVENT_UPDATE_FIELD_NUMBER; hash = (53 * hash) + getEventUpdate().hashCode(); break; case 2: hash = (37 * hash) + CONTROL_FIELD_NUMBER; hash = (53 * hash) + getControl().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.visionai.v1.ReceiveEventsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse 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.ReceiveEventsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse 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.ReceiveEventsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse 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.ReceiveEventsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse 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.ReceiveEventsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse 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.ReceiveEventsResponse 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.ReceiveEventsResponse 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.ReceiveEventsResponse 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 ReceiveEvents. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ReceiveEventsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ReceiveEventsResponse) com.google.cloud.visionai.v1.ReceiveEventsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.StreamingServiceProto .internal_static_google_cloud_visionai_v1_ReceiveEventsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.StreamingServiceProto .internal_static_google_cloud_visionai_v1_ReceiveEventsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ReceiveEventsResponse.class, com.google.cloud.visionai.v1.ReceiveEventsResponse.Builder.class); } // Construct using com.google.cloud.visionai.v1.ReceiveEventsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (eventUpdateBuilder_ != null) { eventUpdateBuilder_.clear(); } if (controlBuilder_ != null) { controlBuilder_.clear(); } responseCase_ = 0; response_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.StreamingServiceProto .internal_static_google_cloud_visionai_v1_ReceiveEventsResponse_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsResponse getDefaultInstanceForType() { return com.google.cloud.visionai.v1.ReceiveEventsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsResponse build() { com.google.cloud.visionai.v1.ReceiveEventsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsResponse buildPartial() { com.google.cloud.visionai.v1.ReceiveEventsResponse result = new com.google.cloud.visionai.v1.ReceiveEventsResponse(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.visionai.v1.ReceiveEventsResponse result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.visionai.v1.ReceiveEventsResponse result) { result.responseCase_ = responseCase_; result.response_ = this.response_; if (responseCase_ == 1 && eventUpdateBuilder_ != null) { result.response_ = eventUpdateBuilder_.build(); } if (responseCase_ == 2 && controlBuilder_ != null) { result.response_ = controlBuilder_.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.visionai.v1.ReceiveEventsResponse) { return mergeFrom((com.google.cloud.visionai.v1.ReceiveEventsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.ReceiveEventsResponse other) { if (other == com.google.cloud.visionai.v1.ReceiveEventsResponse.getDefaultInstance()) return this; switch (other.getResponseCase()) { case EVENT_UPDATE: { mergeEventUpdate(other.getEventUpdate()); break; } case CONTROL: { mergeControl(other.getControl()); break; } case RESPONSE_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(getEventUpdateFieldBuilder().getBuilder(), extensionRegistry); responseCase_ = 1; break; } // case 10 case 18: { input.readMessage(getControlFieldBuilder().getBuilder(), extensionRegistry); responseCase_ = 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 responseCase_ = 0; private java.lang.Object response_; public ResponseCase getResponseCase() { return ResponseCase.forNumber(responseCase_); } public Builder clearResponse() { responseCase_ = 0; response_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.EventUpdate, com.google.cloud.visionai.v1.EventUpdate.Builder, com.google.cloud.visionai.v1.EventUpdateOrBuilder> eventUpdateBuilder_; /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> * * @return Whether the eventUpdate field is set. */ @java.lang.Override public boolean hasEventUpdate() { return responseCase_ == 1; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> * * @return The eventUpdate. */ @java.lang.Override public com.google.cloud.visionai.v1.EventUpdate getEventUpdate() { if (eventUpdateBuilder_ == null) { if (responseCase_ == 1) { return (com.google.cloud.visionai.v1.EventUpdate) response_; } return com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } else { if (responseCase_ == 1) { return eventUpdateBuilder_.getMessage(); } return com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ public Builder setEventUpdate(com.google.cloud.visionai.v1.EventUpdate value) { if (eventUpdateBuilder_ == null) { if (value == null) { throw new NullPointerException(); } response_ = value; onChanged(); } else { eventUpdateBuilder_.setMessage(value); } responseCase_ = 1; return this; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ public Builder setEventUpdate( com.google.cloud.visionai.v1.EventUpdate.Builder builderForValue) { if (eventUpdateBuilder_ == null) { response_ = builderForValue.build(); onChanged(); } else { eventUpdateBuilder_.setMessage(builderForValue.build()); } responseCase_ = 1; return this; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ public Builder mergeEventUpdate(com.google.cloud.visionai.v1.EventUpdate value) { if (eventUpdateBuilder_ == null) { if (responseCase_ == 1 && response_ != com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance()) { response_ = com.google.cloud.visionai.v1.EventUpdate.newBuilder( (com.google.cloud.visionai.v1.EventUpdate) response_) .mergeFrom(value) .buildPartial(); } else { response_ = value; } onChanged(); } else { if (responseCase_ == 1) { eventUpdateBuilder_.mergeFrom(value); } else { eventUpdateBuilder_.setMessage(value); } } responseCase_ = 1; return this; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ public Builder clearEventUpdate() { if (eventUpdateBuilder_ == null) { if (responseCase_ == 1) { responseCase_ = 0; response_ = null; onChanged(); } } else { if (responseCase_ == 1) { responseCase_ = 0; response_ = null; } eventUpdateBuilder_.clear(); } return this; } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ public com.google.cloud.visionai.v1.EventUpdate.Builder getEventUpdateBuilder() { return getEventUpdateFieldBuilder().getBuilder(); } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.EventUpdateOrBuilder getEventUpdateOrBuilder() { if ((responseCase_ == 1) && (eventUpdateBuilder_ != null)) { return eventUpdateBuilder_.getMessageOrBuilder(); } else { if (responseCase_ == 1) { return (com.google.cloud.visionai.v1.EventUpdate) response_; } return com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } } /** * * * <pre> * The event update message. * </pre> * * <code>.google.cloud.visionai.v1.EventUpdate event_update = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.EventUpdate, com.google.cloud.visionai.v1.EventUpdate.Builder, com.google.cloud.visionai.v1.EventUpdateOrBuilder> getEventUpdateFieldBuilder() { if (eventUpdateBuilder_ == null) { if (!(responseCase_ == 1)) { response_ = com.google.cloud.visionai.v1.EventUpdate.getDefaultInstance(); } eventUpdateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.EventUpdate, com.google.cloud.visionai.v1.EventUpdate.Builder, com.google.cloud.visionai.v1.EventUpdateOrBuilder>( (com.google.cloud.visionai.v1.EventUpdate) response_, getParentForChildren(), isClean()); response_ = null; } responseCase_ = 1; onChanged(); return eventUpdateBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.ReceiveEventsControlResponse, com.google.cloud.visionai.v1.ReceiveEventsControlResponse.Builder, com.google.cloud.visionai.v1.ReceiveEventsControlResponseOrBuilder> controlBuilder_; /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> * * @return Whether the control field is set. */ @java.lang.Override public boolean hasControl() { return responseCase_ == 2; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> * * @return The control. */ @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsControlResponse getControl() { if (controlBuilder_ == null) { if (responseCase_ == 2) { return (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_; } return com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance(); } else { if (responseCase_ == 2) { return controlBuilder_.getMessage(); } return com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance(); } } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ public Builder setControl(com.google.cloud.visionai.v1.ReceiveEventsControlResponse value) { if (controlBuilder_ == null) { if (value == null) { throw new NullPointerException(); } response_ = value; onChanged(); } else { controlBuilder_.setMessage(value); } responseCase_ = 2; return this; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ public Builder setControl( com.google.cloud.visionai.v1.ReceiveEventsControlResponse.Builder builderForValue) { if (controlBuilder_ == null) { response_ = builderForValue.build(); onChanged(); } else { controlBuilder_.setMessage(builderForValue.build()); } responseCase_ = 2; return this; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ public Builder mergeControl(com.google.cloud.visionai.v1.ReceiveEventsControlResponse value) { if (controlBuilder_ == null) { if (responseCase_ == 2 && response_ != com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance()) { response_ = com.google.cloud.visionai.v1.ReceiveEventsControlResponse.newBuilder( (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_) .mergeFrom(value) .buildPartial(); } else { response_ = value; } onChanged(); } else { if (responseCase_ == 2) { controlBuilder_.mergeFrom(value); } else { controlBuilder_.setMessage(value); } } responseCase_ = 2; return this; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ public Builder clearControl() { if (controlBuilder_ == null) { if (responseCase_ == 2) { responseCase_ = 0; response_ = null; onChanged(); } } else { if (responseCase_ == 2) { responseCase_ = 0; response_ = null; } controlBuilder_.clear(); } return this; } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ public com.google.cloud.visionai.v1.ReceiveEventsControlResponse.Builder getControlBuilder() { return getControlFieldBuilder().getBuilder(); } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsControlResponseOrBuilder getControlOrBuilder() { if ((responseCase_ == 2) && (controlBuilder_ != null)) { return controlBuilder_.getMessageOrBuilder(); } else { if (responseCase_ == 2) { return (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_; } return com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance(); } } /** * * * <pre> * A control message from the server. * </pre> * * <code>.google.cloud.visionai.v1.ReceiveEventsControlResponse control = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.ReceiveEventsControlResponse, com.google.cloud.visionai.v1.ReceiveEventsControlResponse.Builder, com.google.cloud.visionai.v1.ReceiveEventsControlResponseOrBuilder> getControlFieldBuilder() { if (controlBuilder_ == null) { if (!(responseCase_ == 2)) { response_ = com.google.cloud.visionai.v1.ReceiveEventsControlResponse.getDefaultInstance(); } controlBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.visionai.v1.ReceiveEventsControlResponse, com.google.cloud.visionai.v1.ReceiveEventsControlResponse.Builder, com.google.cloud.visionai.v1.ReceiveEventsControlResponseOrBuilder>( (com.google.cloud.visionai.v1.ReceiveEventsControlResponse) response_, getParentForChildren(), isClean()); response_ = null; } responseCase_ = 2; onChanged(); return controlBuilder_; } @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.ReceiveEventsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ReceiveEventsResponse) private static final com.google.cloud.visionai.v1.ReceiveEventsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ReceiveEventsResponse(); } public static com.google.cloud.visionai.v1.ReceiveEventsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ReceiveEventsResponse> PARSER = new com.google.protobuf.AbstractParser<ReceiveEventsResponse>() { @java.lang.Override public ReceiveEventsResponse 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<ReceiveEventsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ReceiveEventsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.ReceiveEventsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/paimon
34,818
paimon-flink/paimon-flink-common/src/test/java/org/apache/paimon/flink/PostponeBucketTableITCase.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.paimon.flink; import org.apache.paimon.flink.util.AbstractTestBase; import org.apache.flink.core.execution.JobClient; import org.apache.flink.table.api.TableEnvironment; import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.config.TableConfigOptions; import org.apache.flink.types.Row; import org.apache.flink.util.CloseableIterator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** IT cases for postpone bucket tables. */ public class PostponeBucketTableITCase extends AbstractTestBase { private static final int TIMEOUT = 120; @Test public void testRetractOnPartialUpdate() { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v1 INT,\n" + " v2 INT,\n" + " row_kind_col STRING,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2',\n" + " 'merge-engine' = 'partial-update',\n" + " 'rowkind.field' = 'row_kind_col'\n" + ")"); assertThatThrownBy(() -> tEnv.executeSql("INSERT INTO T VALUES (1, 1, 1, '-D')").await()) .rootCause() .hasMessageContaining("By default, Partial update can not accept delete records"); } @Test public void testWriteThenCompact() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " pt INT,\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (pt, k) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2'\n" + ")"); int numPartitions = 3; int numKeys = 100; List<String> values = new ArrayList<>(); for (int i = 0; i < numPartitions; i++) { for (int j = 0; j < numKeys; j++) { values.add(String.format("(%d, %d, %d)", i, j, i * numKeys + j)); } } ThreadLocalRandom random = ThreadLocalRandom.current(); if (random.nextBoolean()) { tEnv.executeSql("INSERT INTO T VALUES " + String.join(", ", values)).await(); } else { tEnv.executeSql( "INSERT INTO T /*+ OPTIONS('partition.sink-strategy'='hash') */ VALUES " + String.join(", ", values)) .await(); } assertThat(collect(tEnv.executeSql("SELECT * FROM T"))).isEmpty(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); List<String> expected = new ArrayList<>(); for (int i = 0; i < numPartitions; i++) { expected.add( String.format( "+I[%d, %d]", i, (i * numKeys + i * numKeys + numKeys - 1) * numKeys / 2)); } String query = "SELECT pt, SUM(v) FROM T GROUP BY pt"; assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expected); values.clear(); int changedPartition = 1; for (int j = 0; j < numKeys; j++) { values.add( String.format( "(%d, %d, %d)", changedPartition, j, -(changedPartition * numKeys + j))); } tEnv.executeSql("INSERT INTO T VALUES " + String.join(", ", values)).await(); assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expected); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); expected.clear(); for (int i = 0; i < numPartitions; i++) { int val = (i * numKeys + i * numKeys + numKeys - 1) * numKeys / 2; if (i == changedPartition) { val *= -1; } expected.add(String.format("+I[%d, %d]", i, val)); } assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expected); } @Test public void testOverwrite() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " pt INT,\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (pt, k) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2'\n" + ")"); tEnv.executeSql( "INSERT INTO T VALUES (1, 10, 110), (1, 20, 120), (2, 10, 210), (2, 20, 220)") .await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))).isEmpty(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 120, 1]", "+I[10, 210, 2]", "+I[20, 220, 2]"); // no compact, so the result is the same tEnv.executeSql("INSERT INTO T VALUES (2, 40, 240)").await(); assertThat(collect(tEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 120, 1]", "+I[10, 210, 2]", "+I[20, 220, 2]"); tEnv.executeSql("INSERT OVERWRITE T VALUES (2, 20, 221), (2, 30, 230)").await(); assertThat(collect(tEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder("+I[10, 110, 1]", "+I[20, 120, 1]"); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); // overwrite should also clean up files in bucket = -2 directory, // which the record with key = 40 assertThat(collect(tEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 120, 1]", "+I[20, 221, 2]", "+I[30, 230, 2]"); } @Timeout(TIMEOUT) @Test public void testLookupChangelogProducer() throws Exception { String warehouse = getTempDirPath(); TableEnvironment bEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); String createCatalogSql = "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"; bEnv.executeSql(createCatalogSql); bEnv.executeSql("USE CATALOG mycat"); bEnv.executeSql( "CREATE TABLE T (\n" + " pt INT,\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (pt, k) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2',\n" + " 'changelog-producer' = 'lookup'\n" + ")"); TableEnvironment sEnv = tableEnvironmentBuilder() .streamingMode() .parallelism(1) .checkpointIntervalMs(1000) .build(); sEnv.executeSql(createCatalogSql); sEnv.executeSql("USE CATALOG mycat"); TableResult streamingSelect = sEnv.executeSql("SELECT k, v, pt FROM T"); JobClient client = streamingSelect.getJobClient().get(); CloseableIterator<Row> it = streamingSelect.collect(); bEnv.executeSql( "INSERT INTO T VALUES (1, 10, 110), (1, 20, 120), (2, 10, 210), (2, 20, 220)") .await(); assertThat(collect(bEnv.executeSql("SELECT * FROM T"))).isEmpty(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(bEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 120, 1]", "+I[10, 210, 2]", "+I[20, 220, 2]"); assertThat(collect(client, it, 4)) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 120, 1]", "+I[10, 210, 2]", "+I[20, 220, 2]"); bEnv.executeSql("INSERT INTO T VALUES (1, 20, 121), (2, 30, 230)").await(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(bEnv.executeSql("SELECT k, v, pt FROM T"))) .containsExactlyInAnyOrder( "+I[10, 110, 1]", "+I[20, 121, 1]", "+I[10, 210, 2]", "+I[20, 220, 2]", "+I[30, 230, 2]"); assertThat(collect(client, it, 3)) .containsExactlyInAnyOrder("-U[20, 120, 1]", "+U[20, 121, 1]", "+I[30, 230, 2]"); it.close(); } @Test public void testRescaleBucket() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " pt INT,\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (pt, k) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2',\n" + " 'postpone.default-bucket-num' = '2'\n" + ")"); int numKeys = 100; List<String> values = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < numKeys; j++) { values.add(String.format("(%d, %d, %d)", i, j, i * numKeys + j)); } } tEnv.executeSql("INSERT INTO T VALUES " + String.join(", ", values)).await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); List<String> expectedBuckets = new ArrayList<>(); for (int i = 0; i < 3; i++) { expectedBuckets.add(String.format("+I[{%d}, 2]", i)); } String bucketSql = "SELECT `partition`, COUNT(DISTINCT bucket) FROM `T$files` GROUP BY `partition`"; assertThat(collect(tEnv.executeSql(bucketSql))).hasSameElementsAs(expectedBuckets); List<String> expectedData = new ArrayList<>(); for (int i = 0; i < 3; i++) { expectedData.add( String.format( "+I[%d, %d]", i, (i * numKeys + i * numKeys + numKeys - 1) * numKeys / 2)); } String query = "SELECT pt, SUM(v) FROM T GROUP BY pt"; assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expectedData); // before rescaling, write some files in bucket = -2 directory, // these files should not be touched by rescaling values.clear(); for (int j = 0; j < numKeys; j++) { values.add(String.format("(1, %d, 0)", j)); values.add(String.format("(2, %d, 1)", j)); } tEnv.executeSql("INSERT INTO T VALUES " + String.join(", ", values)).await(); tEnv.executeSql( "CALL sys.rescale(`table` => 'default.T', `bucket_num` => 4, `partition` => 'pt=1')"); tEnv.executeSql( "CALL sys.rescale(`table` => 'default.T', `bucket_num` => 8, `partition` => 'pt=2')"); expectedBuckets.clear(); expectedBuckets.add("+I[{0}, 2]"); expectedBuckets.add("+I[{1}, 4]"); expectedBuckets.add("+I[{2}, 8]"); assertThat(collect(tEnv.executeSql(bucketSql))).hasSameElementsAs(expectedBuckets); assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expectedData); // rescaling bucket should not touch the files in bucket = -2 directory tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql(bucketSql))).hasSameElementsAs(expectedBuckets); expectedData.clear(); expectedData.add(String.format("+I[0, %d]", (numKeys - 1) * numKeys / 2)); expectedData.add("+I[1, 0]"); expectedData.add(String.format("+I[2, %d]", numKeys)); assertThat(collect(tEnv.executeSql(query))).hasSameElementsAs(expectedData); } @Timeout(TIMEOUT) @Test public void testInputChangelogProducer() throws Exception { String warehouse = getTempDirPath(); TableEnvironment sEnv = tableEnvironmentBuilder() .streamingMode() .parallelism(1) .checkpointIntervalMs(500) .build(); String createCatalog = "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"; sEnv.executeSql(createCatalog); sEnv.executeSql("USE CATALOG mycat"); sEnv.executeSql( "CREATE TEMPORARY TABLE S (\n" + " i INT\n" + ") WITH (\n" + " 'connector' = 'datagen',\n" + " 'fields.i.kind' = 'sequence',\n" + " 'fields.i.start' = '0',\n" + " 'fields.i.end' = '199',\n" + " 'number-of-rows' = '200',\n" + " 'rows-per-second' = '50'\n" + ")"); sEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2',\n" + " 'changelog-producer' = 'input',\n" + " 'continuous.discovery-interval' = '1ms'\n" + ")"); sEnv.executeSql( "CREATE TEMPORARY VIEW V AS SELECT MOD(i, 2) AS x, IF(MOD(i, 2) = 0, 1, 1000) AS y FROM S"); sEnv.executeSql("INSERT INTO T SELECT SUM(y), x FROM V GROUP BY x").await(); TableEnvironment bEnv = tableEnvironmentBuilder() .batchMode() .parallelism(2) .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); bEnv.executeSql(createCatalog); bEnv.executeSql("USE CATALOG mycat"); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); // if the read order when compacting is wrong, this check will fail assertThat(collect(bEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder("+U[100, 0]", "+U[100000, 1]"); TableResult streamingSelect = sEnv.executeSql("SELECT * FROM T /*+ OPTIONS('scan.snapshot-id' = '1') */"); JobClient client = streamingSelect.getJobClient().get(); CloseableIterator<Row> it = streamingSelect.collect(); // if the number of changelog is not sufficient, this call will fail collect(client, it, 400 - 2); } @Test public void testPostponeWriteNotExpireSnapshots() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " pt INT,\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (pt, k) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2',\n" + " 'snapshot.num-retained.min' = '3',\n" + " 'snapshot.num-retained.max' = '3'\n" + ")"); for (int i = 0; i < 5; i++) { tEnv.executeSql(String.format("INSERT INTO T VALUES (%d, 0, 0)", i)).await(); } assertThat(collect(tEnv.executeSql("SELECT COUNT(*) FROM `T$snapshots`"))) .containsExactlyInAnyOrder("+I[5]"); } @Timeout(TIMEOUT) @Test public void testLookupPostponeBucketTable() throws Exception { String warehouse = getTempDirPath(); TableEnvironment bEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); String createCatalogSql = "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"; bEnv.executeSql(createCatalogSql); bEnv.executeSql("USE CATALOG mycat"); bEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2'\n" + ")"); bEnv.executeSql("CREATE TABLE SRC (i INT, `proctime` AS PROCTIME())"); TableEnvironment sEnv = tableEnvironmentBuilder() .streamingMode() .parallelism(1) .checkpointIntervalMs(200) .build(); sEnv.executeSql(createCatalogSql); sEnv.executeSql("USE CATALOG mycat"); TableResult streamingSelect = sEnv.executeSql( "SELECT i, v FROM SRC LEFT JOIN T " + "FOR SYSTEM_TIME AS OF SRC.proctime AS D ON SRC.i = D.k"); JobClient client = streamingSelect.getJobClient().get(); CloseableIterator<Row> it = streamingSelect.collect(); bEnv.executeSql("INSERT INTO T VALUES (1, 10), (2, 20), (3, 30)").await(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); // lookup join bEnv.executeSql("INSERT INTO SRC VALUES (1), (2), (3)").await(); assertThat(collect(client, it, 3)) .containsExactlyInAnyOrder("+I[1, 10]", "+I[2, 20]", "+I[3, 30]"); // rescale and re-join bEnv.executeSql("CALL sys.rescale(`table` => 'default.T', `bucket_num` => 5)").await(); bEnv.executeSql("INSERT INTO SRC VALUES (1), (2), (3)").await(); assertThat(collect(client, it, 3)) .containsExactlyInAnyOrder("+I[1, 10]", "+I[2, 20]", "+I[3, 30]"); it.close(); } @Timeout(TIMEOUT) @Test public void testLookupPostponeBucketPartitionedTable() throws Exception { String warehouse = getTempDirPath(); TableEnvironment bEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); String createCatalogSql = "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"; bEnv.executeSql(createCatalogSql); bEnv.executeSql("USE CATALOG mycat"); bEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " pt INT,\n" + " v INT,\n" + " PRIMARY KEY (k, pt) NOT ENFORCED\n" + ") PARTITIONED BY (pt) WITH (\n" + " 'bucket' = '-2'\n" + ")"); bEnv.executeSql("CREATE TABLE SRC (i INT, pt INT, `proctime` AS PROCTIME())"); TableEnvironment sEnv = tableEnvironmentBuilder() .streamingMode() .parallelism(1) .checkpointIntervalMs(200) .build(); sEnv.executeSql(createCatalogSql); sEnv.executeSql("USE CATALOG mycat"); TableResult streamingSelect = sEnv.executeSql( "SELECT i, D.pt, v FROM SRC LEFT JOIN T " + "FOR SYSTEM_TIME AS OF SRC.proctime AS D ON SRC.i = D.k AND SRC.pt = D.pt"); JobClient client = streamingSelect.getJobClient().get(); CloseableIterator<Row> it = streamingSelect.collect(); bEnv.executeSql("INSERT INTO T VALUES (1, 1, 10), (2, 2, 20), (3, 2, 30)").await(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); // rescale for partitions to different num buckets and lookup join bEnv.executeSql( "CALL sys.rescale(`table` => 'default.T', `bucket_num` => 5, `partition` => 'pt=1')") .await(); bEnv.executeSql( "CALL sys.rescale(`table` => 'default.T', `bucket_num` => 8, `partition` => 'pt=2')") .await(); bEnv.executeSql("INSERT INTO SRC VALUES (1, 1), (2, 2), (3, 2)").await(); assertThat(collect(client, it, 3)) .containsExactlyInAnyOrder("+I[1, 1, 10]", "+I[2, 2, 20]", "+I[3, 2, 30]"); it.close(); } @Test public void testDeletionVector() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2',\n" + " 'deletion-vectors.enabled' = 'true'\n" + ")"); tEnv.executeSql("INSERT INTO T VALUES (1, 10), (2, 20), (3, 30), (4, 40)").await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder("+I[1, 10]", "+I[2, 20]", "+I[3, 30]", "+I[4, 40]"); tEnv.executeSql("INSERT INTO T VALUES (1, 11), (5, 51)").await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder( "+I[1, 11]", "+I[2, 20]", "+I[3, 30]", "+I[4, 40]", "+I[5, 51]"); tEnv.executeSql("INSERT INTO T VALUES (2, 52), (3, 32)").await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder( "+I[1, 11]", "+I[2, 52]", "+I[3, 32]", "+I[4, 40]", "+I[5, 51]"); } @Test public void testSameKeyPreserveOrder() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2'\n" + ")"); tEnv.executeSql( "INSERT INTO T /*+ OPTIONS('sink.parallelism' = '2') */ VALUES (1, 10), (1, 20), (1, 30), (1, 40)") .await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder("+I[1, 40]"); } @Test public void testAvroUnsupportedTypes() throws Exception { String warehouse = getTempDirPath(); TableEnvironment tEnv = tableEnvironmentBuilder() .batchMode() .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); tEnv.executeSql( "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"); tEnv.executeSql("USE CATALOG mycat"); tEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v TIMESTAMP(9),\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2'\n" + ")"); tEnv.executeSql( "INSERT INTO T VALUES (1, TIMESTAMP '2025-06-11 16:35:45.123456789'), (2, CAST(NULL AS TIMESTAMP(9)))") .await(); tEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(tEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder("+I[1, 2025-06-11T16:35:45.123456789]", "+I[2, null]"); } @Timeout(TIMEOUT) @Test public void testNoneChangelogProducer() throws Exception { String warehouse = getTempDirPath(); TableEnvironment sEnv = tableEnvironmentBuilder() .streamingMode() .parallelism(2) .checkpointIntervalMs(500) .build(); String createCatalog = "CREATE CATALOG mycat WITH (\n" + " 'type' = 'paimon',\n" + " 'warehouse' = '" + warehouse + "'\n" + ")"; sEnv.executeSql(createCatalog); sEnv.executeSql("USE CATALOG mycat"); sEnv.executeSql( "CREATE TABLE T (\n" + " k INT,\n" + " v INT,\n" + " PRIMARY KEY (k) NOT ENFORCED\n" + ") WITH (\n" + " 'bucket' = '-2',\n" + " 'changelog-producer' = 'none',\n" + " 'scan.remove-normalize' = 'true',\n" + " 'continuous.discovery-interval' = '1ms'\n" + ")"); TableEnvironment bEnv = tableEnvironmentBuilder() .batchMode() .parallelism(1) .setConf(TableConfigOptions.TABLE_DML_SYNC, true) .build(); bEnv.executeSql(createCatalog); bEnv.executeSql("USE CATALOG mycat"); bEnv.executeSql("INSERT INTO T VALUES (1, 10), (2, 20), (1, 100)").await(); bEnv.executeSql("INSERT INTO T VALUES (1, 101), (3, 31)").await(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); TableResult streamingSelect = sEnv.executeSql("SELECT * FROM T"); Thread.sleep(1000); bEnv.executeSql("INSERT INTO T VALUES (1, 102), (4, 42)").await(); bEnv.executeSql("INSERT INTO T VALUES (1, 103), (5, 53)").await(); bEnv.executeSql("CALL sys.compact(`table` => 'default.T')").await(); assertThat(collect(bEnv.executeSql("SELECT * FROM T"))) .containsExactlyInAnyOrder( "+I[1, 103]", "+I[2, 20]", "+I[3, 31]", "+I[4, 42]", "+I[5, 53]"); JobClient client = streamingSelect.getJobClient().get(); CloseableIterator<Row> it = streamingSelect.collect(); assertThat(collect(client, it, 7)) .containsExactlyInAnyOrder( "+I[1, 101]", "+I[2, 20]", "+I[3, 31]", "+I[1, 102]", "+I[4, 42]", "+I[1, 103]", "+I[5, 53]"); } private List<String> collect(TableResult result) throws Exception { List<String> ret = new ArrayList<>(); try (CloseableIterator<Row> it = result.collect()) { while (it.hasNext()) { ret.add(it.next().toString()); } } return ret; } private List<String> collect(JobClient client, CloseableIterator<Row> it, int limit) throws Exception { AtomicBoolean shouldStop = new AtomicBoolean(false); Thread timerThread = new Thread( () -> { try { for (int i = 0; i < TIMEOUT; i++) { Thread.sleep(1000); if (shouldStop.get()) { return; } } client.cancel().get(); } catch (Exception e) { throw new RuntimeException(e); } }); timerThread.start(); List<String> ret = new ArrayList<>(); for (int i = 0; i < limit && it.hasNext(); i++) { ret.add(it.next().toString()); } shouldStop.set(true); timerThread.join(); return ret; } }
google/ExoPlayer
35,687
library/core/src/test/java/com/google/android/exoplayer2/DefaultLivePlaybackSpeedControlTest.java
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2; import static com.google.common.truth.Truth.assertThat; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.MediaItem.LiveConfiguration; import com.google.common.collect.Iterables; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.shadows.ShadowSystemClock; /** Unit test for {@link DefaultLivePlaybackSpeedControl}. */ @RunWith(AndroidJUnit4.class) public class DefaultLivePlaybackSpeedControlTest { @Test public void getTargetLiveOffsetUs_returnsUnset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); assertThat(defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs()).isEqualTo(C.TIME_UNSET); } @Test public void getTargetLiveOffsetUs_afterSetLiveConfiguration_returnsMediaLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); assertThat(defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs()).isEqualTo(42_000); } @Test public void getTargetLiveOffsetUs_afterSetLiveConfigurationWithTargetGreaterThanMax_returnsMaxLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(4321) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); assertThat(defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs()).isEqualTo(400_000); } @Test public void getTargetLiveOffsetUs_afterSetLiveConfigurationWithTargetLessThanMin_returnsMinLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(3) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); assertThat(defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs()).isEqualTo(5_000); } @Test public void getTargetLiveOffsetUs_afterSetTargetLiveOffsetOverrideUs_returnsOverride() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(321_000); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(321_000); } @Test public void getTargetLiveOffsetUs_afterSetTargetLiveOffsetOverrideUsGreaterThanMax_returnsMaxLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(123_456_789); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(400_000); } @Test public void getTargetLiveOffsetUs_afterSetTargetLiveOffsetOverrideUsLessThanMin_returnsMinLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(3_141); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(5_000); } @Test public void getTargetLiveOffsetUs_afterSetTargetLiveOffsetOverrideWithoutMediaConfiguration_returnsUnset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(123_456_789); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(C.TIME_UNSET); } @Test public void getTargetLiveOffsetUs_withUnitSpeed_returnsUnset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinPlaybackSpeed(1f) .setMaxPlaybackSpeed(1f) .build()); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(C.TIME_UNSET); } @Test public void getTargetLiveOffsetUs_afterSetTargetLiveOffsetOverrideWithTimeUnset_returnsMediaLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(123_456_789); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(C.TIME_UNSET); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(42_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebuffer_returnsIncreasedTargetOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); long targetLiveOffsetBeforeUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); defaultLivePlaybackSpeedControl.notifyRebuffer(); long targetLiveOffsetAfterUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetAfterUs).isGreaterThan(targetLiveOffsetBeforeUs); assertThat(targetLiveOffsetAfterUs - targetLiveOffsetBeforeUs).isEqualTo(3_000); } @Test public void getTargetLiveOffsetUs_afterRepeatedNotifyRebuffer_returnsMaxLiveOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); List<Long> targetOffsetsUs = new ArrayList<>(); for (int i = 0; i < 500; i++) { targetOffsetsUs.add(defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs()); defaultLivePlaybackSpeedControl.notifyRebuffer(); } assertThat(targetOffsetsUs).isInOrder(); assertThat(Iterables.getLast(targetOffsetsUs)).isEqualTo(400_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferWithIncrementOfZero_returnsOriginalTargetOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(0) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); defaultLivePlaybackSpeedControl.notifyRebuffer(); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(42_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferAndSetTargetLiveOffsetOverrideUs_returnsOverride() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); defaultLivePlaybackSpeedControl.notifyRebuffer(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(321_000); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(321_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferAndSetLiveConfigurationWithSameOffset_returnsIncreasedTargetOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); long targetLiveOffsetBeforeUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); defaultLivePlaybackSpeedControl.notifyRebuffer(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(3) .setMaxOffsetMs(450) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); long targetLiveOffsetAfterUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetAfterUs).isGreaterThan(targetLiveOffsetBeforeUs); assertThat(targetLiveOffsetAfterUs - targetLiveOffsetBeforeUs).isEqualTo(3_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferAndSetLiveConfigurationWithNewOffset_returnsNewOffset() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42) .setMinOffsetMs(5) .setMaxOffsetMs(400) .setMinPlaybackSpeed(0.95f) .setMaxPlaybackSpeed(1.05f) .build()); defaultLivePlaybackSpeedControl.notifyRebuffer(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(39) .setMinOffsetMs(3) .setMaxOffsetMs(450) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); long targetLiveOffsetUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetUs).isEqualTo(39_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferAndAdjustPlaybackSpeedWithLargeBufferedDuration_returnsDecreasedOffsetToIdealTarget() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3_000) .setMinUpdateIntervalMs(100) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42_000) .setMinOffsetMs(5_000) .setMaxOffsetMs(400_000) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); defaultLivePlaybackSpeedControl.notifyRebuffer(); long targetLiveOffsetAfterRebufferUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 45_000_000, /* bufferedDurationUs= */ 9_000_000); long targetLiveOffsetAfterOneAdjustmentUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); for (int i = 0; i < 500; i++) { ShadowSystemClock.advanceBy(Duration.ofMillis(100)); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 45_000_000, /* bufferedDurationUs= */ 9_000_000); } long targetLiveOffsetAfterManyAdjustmentsUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetAfterOneAdjustmentUs).isLessThan(targetLiveOffsetAfterRebufferUs); assertThat(targetLiveOffsetAfterManyAdjustmentsUs) .isLessThan(targetLiveOffsetAfterOneAdjustmentUs); assertThat(targetLiveOffsetAfterManyAdjustmentsUs).isEqualTo(42_000_000); } @Test public void getTargetLiveOffsetUs_afterNotifyRebufferAndAdjustPlaybackSpeedWithSmallBufferedDuration_returnsDecreasedOffsetToSafeTarget() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3_000) .setMinUpdateIntervalMs(100) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42_000) .setMinOffsetMs(5_000) .setMaxOffsetMs(400_000) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); defaultLivePlaybackSpeedControl.notifyRebuffer(); long targetLiveOffsetAfterRebufferUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 45_000_000, /* bufferedDurationUs= */ 1_000_000); long targetLiveOffsetAfterOneAdjustmentUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); for (int i = 0; i < 500; i++) { ShadowSystemClock.advanceBy(Duration.ofMillis(100)); long noiseUs = ((i % 10) - 5L) * 1_000; defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 45_000_000, /* bufferedDurationUs= */ 1_000_000 + noiseUs); } long targetLiveOffsetAfterManyAdjustmentsUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetAfterOneAdjustmentUs).isLessThan(targetLiveOffsetAfterRebufferUs); assertThat(targetLiveOffsetAfterManyAdjustmentsUs) .isLessThan(targetLiveOffsetAfterOneAdjustmentUs); // Should be at least be at the minimum buffered position. assertThat(targetLiveOffsetAfterManyAdjustmentsUs).isGreaterThan(44_005_000); } @Test public void getTargetLiveOffsetUs_afterAdjustPlaybackSpeedWithLiveOffsetAroundCurrentTarget_returnsSafeTarget() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42_000) .setMinOffsetMs(5_000) .setMaxOffsetMs(400_000) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); long targetLiveOffsetBeforeUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); // Pretend to have a buffered duration at around the target duration with some artificial noise. for (int i = 0; i < 500; i++) { ShadowSystemClock.advanceBy(Duration.ofMillis(100)); long noiseUs = ((i % 10) - 5L) * 1_000; defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 49_000_000, /* bufferedDurationUs= */ 7_000_000 + noiseUs); } ShadowSystemClock.advanceBy(Duration.ofMillis(100)); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 49_000_000, /* bufferedDurationUs= */ 7_000_000); long targetLiveOffsetAfterUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetBeforeUs).isEqualTo(42_000_000); assertThat(targetLiveOffsetAfterUs).isGreaterThan(42_005_000); } @Test public void getTargetLiveOffsetUs_afterAdjustPlaybackSpeedAndSmoothingFactorOfZero_ignoresSafeTargetAndReturnsCurrentTarget() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setMinPossibleLiveOffsetSmoothingFactor(0f) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42_000) .setMinOffsetMs(5_000) .setMaxOffsetMs(400_000) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); long targetLiveOffsetBeforeUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); // Pretend to have a buffered duration at around the target duration with some artificial noise. for (int i = 0; i < 500; i++) { ShadowSystemClock.advanceBy(Duration.ofMillis(100)); long noiseUs = ((i % 10) - 5L) * 1_000; defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 49_000_000, /* bufferedDurationUs= */ 7_000_000 + noiseUs); } ShadowSystemClock.advanceBy(Duration.ofMillis(100)); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 49_000_000, /* bufferedDurationUs= */ 7_000_000); long targetLiveOffsetAfterUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetBeforeUs).isEqualTo(42_000_000); // Despite the noise indicating it's unsafe here, we still return the target offset. assertThat(targetLiveOffsetAfterUs).isEqualTo(42_000_000); } @Test public void getTargetLiveOffsetUs_afterAdjustPlaybackSpeedWithLiveOffsetLessThanCurrentTarget_returnsCurrentTarget() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setTargetLiveOffsetIncrementOnRebufferMs(3_000) .setMinUpdateIntervalMs(100) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(42_000) .setMinOffsetMs(5_000) .setMaxOffsetMs(400_000) .setMinPlaybackSpeed(0.9f) .setMaxPlaybackSpeed(1.1f) .build()); long targetLiveOffsetBeforeUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 39_000_000, /* bufferedDurationUs= */ 1_000_000); long targetLiveOffsetAfterUs = defaultLivePlaybackSpeedControl.getTargetLiveOffsetUs(); assertThat(targetLiveOffsetBeforeUs).isEqualTo(42_000_000); assertThat(targetLiveOffsetAfterUs).isEqualTo(42_000_000); } @Test public void adjustPlaybackSpeed_liveOffsetMatchesTargetOffset_returnsUnitSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_000_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed).isEqualTo(1f); } @Test public void adjustPlaybackSpeed_liveOffsetWithinAcceptableErrorMargin_returnsUnitSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder() .setMaxLiveOffsetErrorMsForUnitSpeed(5) .build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeedJustAboveLowerErrorMargin = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_000_000 - 5_000 + 1, /* bufferedDurationUs= */ 1_000_000); float adjustedSpeedJustBelowUpperErrorMargin = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_000_000 + 5_000 - 1, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeedJustAboveLowerErrorMargin).isEqualTo(1f); assertThat(adjustedSpeedJustBelowUpperErrorMargin).isEqualTo(1f); } @Test public void adjustPlaybackSpeed_withLiveOffsetGreaterThanTargetOffset_returnsAdjustedSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setProportionalControlFactor(0.01f).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); float expectedSpeedAccordingToDocumentation = 1f + 0.01f * (2.5f - 2f); assertThat(adjustedSpeed).isEqualTo(expectedSpeedAccordingToDocumentation); assertThat(adjustedSpeed).isGreaterThan(1f); } @Test public void adjustPlaybackSpeed_withLiveOffsetLowerThanTargetOffset_returnsAdjustedSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setProportionalControlFactor(0.01f).build(); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(2_000_000); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); float expectedSpeedAccordingToDocumentation = 1f + 0.01f * (1.5f - 2f); assertThat(adjustedSpeed).isEqualTo(expectedSpeedAccordingToDocumentation); assertThat(adjustedSpeed).isLessThan(1f); } @Test public void adjustPlaybackSpeed_withLiveOffsetGreaterThanTargetOffset_clampedToFallbackMaximumSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setFallbackMaxPlaybackSpeed(1.5f).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 999_999_999_999L, /* bufferedDurationUs= */ 999_999_999_999L); assertThat(adjustedSpeed).isEqualTo(1.5f); } @Test public void adjustPlaybackSpeed_withLiveOffsetLowerThanTargetOffset_clampedToFallbackMinimumSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setFallbackMinPlaybackSpeed(0.5f).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ -999_999_999_999L, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed).isEqualTo(0.5f); } @Test public void adjustPlaybackSpeed_andMediaProvidedMaxSpeedWithLiveOffsetGreaterThanTargetOffset_clampedToMediaMaxSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setFallbackMaxPlaybackSpeed(1.5f).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(2f) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 999_999_999_999L, /* bufferedDurationUs= */ 999_999_999_999L); assertThat(adjustedSpeed).isEqualTo(2f); } @Test public void adjustPlaybackSpeed_andMediaProvidedMinSpeedWithLiveOffsetLowerThanTargetOffset_clampedToMediaMinSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setFallbackMinPlaybackSpeed(0.5f).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(0.2f) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ -999_999_999_999L, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed).isEqualTo(0.2f); } @Test public void adjustPlaybackSpeed_repeatedCallWithinMinUpdateInterval_returnsSameAdjustedSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setMinUpdateIntervalMs(123).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed1 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); ShadowSystemClock.advanceBy(Duration.ofMillis(122)); float adjustedSpeed2 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); ShadowSystemClock.advanceBy(Duration.ofMillis(2)); float adjustedSpeed3 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed1).isEqualTo(adjustedSpeed2); assertThat(adjustedSpeed3).isNotEqualTo(adjustedSpeed2); } @Test public void adjustPlaybackSpeed_repeatedCallAfterSetLiveConfigurationWithSameOffset_returnsSameAdjustedSpeed() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setMinUpdateIntervalMs(123).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed1 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed2 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed1).isEqualTo(adjustedSpeed2); } @Test public void adjustPlaybackSpeed_repeatedCallAfterSetLiveConfigurationWithNewOffset_updatesSpeedAgain() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setMinUpdateIntervalMs(123).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed1 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(1_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed2 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed1).isNotEqualTo(adjustedSpeed2); } @Test public void adjustPlaybackSpeed_repeatedCallAfterSetTargetLiveOffsetOverrideUs_updatesSpeedAgain() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setMinUpdateIntervalMs(123).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed1 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); defaultLivePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(2_000_001); float adjustedSpeed2 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed1).isNotEqualTo(adjustedSpeed2); } @Test public void adjustPlaybackSpeed_repeatedCallAfterNotifyRebuffer_updatesSpeedAgain() { DefaultLivePlaybackSpeedControl defaultLivePlaybackSpeedControl = new DefaultLivePlaybackSpeedControl.Builder().setMinUpdateIntervalMs(123).build(); defaultLivePlaybackSpeedControl.setLiveConfiguration( new LiveConfiguration.Builder() .setTargetOffsetMs(2_000) .setMinOffsetMs(C.TIME_UNSET) .setMaxOffsetMs(C.TIME_UNSET) .setMinPlaybackSpeed(C.RATE_UNSET) .setMaxPlaybackSpeed(C.RATE_UNSET) .build()); float adjustedSpeed1 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 1_500_000, /* bufferedDurationUs= */ 1_000_000); defaultLivePlaybackSpeedControl.notifyRebuffer(); float adjustedSpeed2 = defaultLivePlaybackSpeedControl.getAdjustedPlaybackSpeed( /* liveOffsetUs= */ 2_500_000, /* bufferedDurationUs= */ 1_000_000); assertThat(adjustedSpeed1).isNotEqualTo(adjustedSpeed2); } }
googleads/google-ads-java
35,504
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/CustomerUserAccessInvitationOperation.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/customer_user_access_invitation_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation} */ public final class CustomerUserAccessInvitationOperation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) CustomerUserAccessInvitationOperationOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerUserAccessInvitationOperation.newBuilder() to construct. private CustomerUserAccessInvitationOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerUserAccessInvitationOperation() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerUserAccessInvitationOperation(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v19_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v19_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.Builder.class); } private int operationCase_ = 0; @SuppressWarnings("serial") private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { CREATE(1), REMOVE(2), OPERATION_NOT_SET(0); private final int value; private OperationCase(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 OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return CREATE; case 2: return REMOVE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int CREATE_FIELD_NUMBER = 1; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation getCreate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } public static final int REMOVE_FIELD_NUMBER = 2; /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = 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 (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, operation_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, operation_); } 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.CustomerUserAccessInvitationOperation)) { return super.equals(obj); } com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation other = (com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) obj; if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getCreate() .equals(other.getCreate())) return false; break; case 2: if (!getRemove() .equals(other.getRemove())) 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 (operationCase_) { case 1: hash = (37 * hash) + CREATE_FIELD_NUMBER; hash = (53 * hash) + getCreate().hashCode(); break; case 2: hash = (37 * hash) + REMOVE_FIELD_NUMBER; hash = (53 * hash) + getRemove().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v19_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v19_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.Builder.class); } // Construct using com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (createBuilder_ != null) { createBuilder_.clear(); } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v19_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation build() { com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation buildPartial() { com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation result = new com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation result) { result.operationCase_ = operationCase_; result.operation_ = this.operation_; if (operationCase_ == 1 && createBuilder_ != null) { result.operation_ = createBuilder_.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.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) { return mergeFrom((com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation other) { if (other == com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation.getDefaultInstance()) return this; switch (other.getOperationCase()) { case CREATE: { mergeCreate(other.getCreate()); break; } case REMOVE: { operationCase_ = 2; operation_ = other.operation_; onChanged(); break; } case OPERATION_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( getCreateFieldBuilder().getBuilder(), extensionRegistry); operationCase_ = 1; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); operationCase_ = 2; operation_ = s; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitationOrBuilder> createBuilder_; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation getCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } else { if (operationCase_ == 1) { return createBuilder_.getMessage(); } return com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate(com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; onChanged(); } else { createBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate( com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.Builder builderForValue) { if (createBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { createBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder mergeCreate(com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance()) { operation_ = com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.newBuilder((com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { createBuilder_.mergeFrom(value); } else { createBuilder_.setMessage(value); } } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder clearCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } createBuilder_.clear(); } return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ public com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.Builder getCreateBuilder() { return getCreateFieldBuilder().getBuilder(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if ((operationCase_ == 1) && (createBuilder_ != null)) { return createBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v19.resources.CustomerUserAccessInvitation create = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitationOrBuilder> getCreateFieldBuilder() { if (createBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.getDefaultInstance(); } createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v19.resources.CustomerUserAccessInvitationOrBuilder>( (com.google.ads.googleads.v19.resources.CustomerUserAccessInvitation) operation_, getParentForChildren(), isClean()); operation_ = null; } operationCase_ = 1; onChanged(); return createBuilder_; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ @java.lang.Override public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ @java.lang.Override public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ @java.lang.Override public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The remove to set. * @return This builder for chaining. */ public Builder setRemove( java.lang.String value) { if (value == null) { throw new NullPointerException(); } operationCase_ = 2; operation_ = value; onChanged(); return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearRemove() { if (operationCase_ == 2) { operationCase_ = 0; operation_ = null; onChanged(); } return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The bytes for remove to set. * @return This builder for chaining. */ public Builder setRemoveBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); operationCase_ = 2; operation_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation) private static final com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation(); } public static com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> PARSER = new com.google.protobuf.AbstractParser<CustomerUserAccessInvitationOperation>() { @java.lang.Override public CustomerUserAccessInvitationOperation 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<CustomerUserAccessInvitationOperation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,504
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/CustomerUserAccessInvitationOperation.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/customer_user_access_invitation_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation} */ public final class CustomerUserAccessInvitationOperation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) CustomerUserAccessInvitationOperationOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerUserAccessInvitationOperation.newBuilder() to construct. private CustomerUserAccessInvitationOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerUserAccessInvitationOperation() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerUserAccessInvitationOperation(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v20_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v20_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.Builder.class); } private int operationCase_ = 0; @SuppressWarnings("serial") private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { CREATE(1), REMOVE(2), OPERATION_NOT_SET(0); private final int value; private OperationCase(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 OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return CREATE; case 2: return REMOVE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int CREATE_FIELD_NUMBER = 1; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation getCreate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } public static final int REMOVE_FIELD_NUMBER = 2; /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = 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 (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, operation_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, operation_); } 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.CustomerUserAccessInvitationOperation)) { return super.equals(obj); } com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation other = (com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) obj; if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getCreate() .equals(other.getCreate())) return false; break; case 2: if (!getRemove() .equals(other.getRemove())) 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 (operationCase_) { case 1: hash = (37 * hash) + CREATE_FIELD_NUMBER; hash = (53 * hash) + getCreate().hashCode(); break; case 2: hash = (37 * hash) + REMOVE_FIELD_NUMBER; hash = (53 * hash) + getRemove().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v20_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v20_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.Builder.class); } // Construct using com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (createBuilder_ != null) { createBuilder_.clear(); } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v20_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation build() { com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation buildPartial() { com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation result = new com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation result) { result.operationCase_ = operationCase_; result.operation_ = this.operation_; if (operationCase_ == 1 && createBuilder_ != null) { result.operation_ = createBuilder_.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.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) { return mergeFrom((com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation other) { if (other == com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation.getDefaultInstance()) return this; switch (other.getOperationCase()) { case CREATE: { mergeCreate(other.getCreate()); break; } case REMOVE: { operationCase_ = 2; operation_ = other.operation_; onChanged(); break; } case OPERATION_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( getCreateFieldBuilder().getBuilder(), extensionRegistry); operationCase_ = 1; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); operationCase_ = 2; operation_ = s; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitationOrBuilder> createBuilder_; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation getCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } else { if (operationCase_ == 1) { return createBuilder_.getMessage(); } return com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate(com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; onChanged(); } else { createBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate( com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.Builder builderForValue) { if (createBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { createBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder mergeCreate(com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance()) { operation_ = com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.newBuilder((com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { createBuilder_.mergeFrom(value); } else { createBuilder_.setMessage(value); } } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder clearCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } createBuilder_.clear(); } return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ public com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.Builder getCreateBuilder() { return getCreateFieldBuilder().getBuilder(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if ((operationCase_ == 1) && (createBuilder_ != null)) { return createBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v20.resources.CustomerUserAccessInvitation create = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitationOrBuilder> getCreateFieldBuilder() { if (createBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.getDefaultInstance(); } createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v20.resources.CustomerUserAccessInvitationOrBuilder>( (com.google.ads.googleads.v20.resources.CustomerUserAccessInvitation) operation_, getParentForChildren(), isClean()); operation_ = null; } operationCase_ = 1; onChanged(); return createBuilder_; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ @java.lang.Override public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ @java.lang.Override public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ @java.lang.Override public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The remove to set. * @return This builder for chaining. */ public Builder setRemove( java.lang.String value) { if (value == null) { throw new NullPointerException(); } operationCase_ = 2; operation_ = value; onChanged(); return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearRemove() { if (operationCase_ == 2) { operationCase_ = 0; operation_ = null; onChanged(); } return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The bytes for remove to set. * @return This builder for chaining. */ public Builder setRemoveBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); operationCase_ = 2; operation_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation) private static final com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation(); } public static com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> PARSER = new com.google.protobuf.AbstractParser<CustomerUserAccessInvitationOperation>() { @java.lang.Override public CustomerUserAccessInvitationOperation 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<CustomerUserAccessInvitationOperation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,504
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/CustomerUserAccessInvitationOperation.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/customer_user_access_invitation_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation} */ public final class CustomerUserAccessInvitationOperation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) CustomerUserAccessInvitationOperationOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerUserAccessInvitationOperation.newBuilder() to construct. private CustomerUserAccessInvitationOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerUserAccessInvitationOperation() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerUserAccessInvitationOperation(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v21_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v21_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.Builder.class); } private int operationCase_ = 0; @SuppressWarnings("serial") private java.lang.Object operation_; public enum OperationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { CREATE(1), REMOVE(2), OPERATION_NOT_SET(0); private final int value; private OperationCase(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 OperationCase valueOf(int value) { return forNumber(value); } public static OperationCase forNumber(int value) { switch (value) { case 1: return CREATE; case 2: return REMOVE; case 0: return OPERATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public static final int CREATE_FIELD_NUMBER = 1; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation getCreate() { if (operationCase_ == 1) { return (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if (operationCase_ == 1) { return (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } public static final int REMOVE_FIELD_NUMBER = 2; /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = 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 (operationCase_ == 1) { output.writeMessage(1, (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, operation_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (operationCase_ == 1) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_); } if (operationCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, operation_); } 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.CustomerUserAccessInvitationOperation)) { return super.equals(obj); } com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation other = (com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) obj; if (!getOperationCase().equals(other.getOperationCase())) return false; switch (operationCase_) { case 1: if (!getCreate() .equals(other.getCreate())) return false; break; case 2: if (!getRemove() .equals(other.getRemove())) 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 (operationCase_) { case 1: hash = (37 * hash) + CREATE_FIELD_NUMBER; hash = (53 * hash) + getCreate().hashCode(); break; case 2: hash = (37 * hash) + REMOVE_FIELD_NUMBER; hash = (53 * hash) + getRemove().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation 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.CustomerUserAccessInvitationOperation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A single operation (create or remove) on customer user access invitation. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v21_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v21_services_CustomerUserAccessInvitationOperation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.class, com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.Builder.class); } // Construct using com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (createBuilder_ != null) { createBuilder_.clear(); } operationCase_ = 0; operation_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationServiceProto.internal_static_google_ads_googleads_v21_services_CustomerUserAccessInvitationOperation_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation build() { com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation buildPartial() { com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation result = new com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation result) { result.operationCase_ = operationCase_; result.operation_ = this.operation_; if (operationCase_ == 1 && createBuilder_ != null) { result.operation_ = createBuilder_.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.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) { return mergeFrom((com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation other) { if (other == com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation.getDefaultInstance()) return this; switch (other.getOperationCase()) { case CREATE: { mergeCreate(other.getCreate()); break; } case REMOVE: { operationCase_ = 2; operation_ = other.operation_; onChanged(); break; } case OPERATION_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( getCreateFieldBuilder().getBuilder(), extensionRegistry); operationCase_ = 1; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); operationCase_ = 2; operation_ = s; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int operationCase_ = 0; private java.lang.Object operation_; public OperationCase getOperationCase() { return OperationCase.forNumber( operationCase_); } public Builder clearOperation() { operationCase_ = 0; operation_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitationOrBuilder> createBuilder_; /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> * @return Whether the create field is set. */ @java.lang.Override public boolean hasCreate() { return operationCase_ == 1; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> * @return The create. */ @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation getCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { return (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } else { if (operationCase_ == 1) { return createBuilder_.getMessage(); } return com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate(com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; onChanged(); } else { createBuilder_.setMessage(value); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder setCreate( com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.Builder builderForValue) { if (createBuilder_ == null) { operation_ = builderForValue.build(); onChanged(); } else { createBuilder_.setMessage(builderForValue.build()); } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder mergeCreate(com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation value) { if (createBuilder_ == null) { if (operationCase_ == 1 && operation_ != com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance()) { operation_ = com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.newBuilder((com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_) .mergeFrom(value).buildPartial(); } else { operation_ = value; } onChanged(); } else { if (operationCase_ == 1) { createBuilder_.mergeFrom(value); } else { createBuilder_.setMessage(value); } } operationCase_ = 1; return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ public Builder clearCreate() { if (createBuilder_ == null) { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; onChanged(); } } else { if (operationCase_ == 1) { operationCase_ = 0; operation_ = null; } createBuilder_.clear(); } return this; } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ public com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.Builder getCreateBuilder() { return getCreateFieldBuilder().getBuilder(); } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerUserAccessInvitationOrBuilder getCreateOrBuilder() { if ((operationCase_ == 1) && (createBuilder_ != null)) { return createBuilder_.getMessageOrBuilder(); } else { if (operationCase_ == 1) { return (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_; } return com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } } /** * <pre> * Create operation: No resource name is expected for the new access * invitation. * </pre> * * <code>.google.ads.googleads.v21.resources.CustomerUserAccessInvitation create = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitationOrBuilder> getCreateFieldBuilder() { if (createBuilder_ == null) { if (!(operationCase_ == 1)) { operation_ = com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.getDefaultInstance(); } createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation.Builder, com.google.ads.googleads.v21.resources.CustomerUserAccessInvitationOrBuilder>( (com.google.ads.googleads.v21.resources.CustomerUserAccessInvitation) operation_, getParentForChildren(), isClean()); operation_ = null; } operationCase_ = 1; onChanged(); return createBuilder_; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return Whether the remove field is set. */ @java.lang.Override public boolean hasRemove() { return operationCase_ == 2; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The remove. */ @java.lang.Override public java.lang.String getRemove() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (operationCase_ == 2) { operation_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for remove. */ @java.lang.Override public com.google.protobuf.ByteString getRemoveBytes() { java.lang.Object ref = ""; if (operationCase_ == 2) { ref = operation_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); if (operationCase_ == 2) { operation_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The remove to set. * @return This builder for chaining. */ public Builder setRemove( java.lang.String value) { if (value == null) { throw new NullPointerException(); } operationCase_ = 2; operation_ = value; onChanged(); return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearRemove() { if (operationCase_ == 2) { operationCase_ = 0; operation_ = null; onChanged(); } return this; } /** * <pre> * Remove operation: A resource name for the revoke invitation is * expected, in this format: * * `customers/{customer_id}/customerUserAccessInvitations/{invitation_id}` * </pre> * * <code>string remove = 2 [(.google.api.resource_reference) = { ... }</code> * @param value The bytes for remove to set. * @return This builder for chaining. */ public Builder setRemoveBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); operationCase_ = 2; operation_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation) private static final com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation(); } public static com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> PARSER = new com.google.protobuf.AbstractParser<CustomerUserAccessInvitationOperation>() { @java.lang.Override public CustomerUserAccessInvitationOperation 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<CustomerUserAccessInvitationOperation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerUserAccessInvitationOperation> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.CustomerUserAccessInvitationOperation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/tomee
35,590
container/openejb-core/src/main/java/org/apache/openejb/math/util/ResizableDoubleArray.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.math.util; import org.apache.openejb.math.MathRuntimeException; import java.io.Serializable; import java.util.Arrays; /** * <p> * A variable length {@link DoubleArray} implementation that automatically * handles expanding and contracting its internal storage array as elements * are added and removed. * </p> * <p> * The internal storage array starts with capacity determined by the * <code>initialCapacity</code> property, which can be set by the constructor. * The default initial capacity is 16. Adding elements using * {@link #addElement(double)} appends elements to the end of the array. When * there are no open entries at the end of the internal storage array, the * array is expanded. The size of the expanded array depends on the * <code>expansionMode</code> and <code>expansionFactor</code> properties. * The <code>expansionMode</code> determines whether the size of the array is * multiplied by the <code>expansionFactor</code> (MULTIPLICATIVE_MODE) or if * the expansion is additive (ADDITIVE_MODE -- <code>expansionFactor</code> * storage locations added). The default <code>expansionMode</code> is * MULTIPLICATIVE_MODE and the default <code>expansionFactor</code> * is 2.0. * </p> * <p> * The {@link #addElementRolling(double)} method adds a new element to the end * of the internal storage array and adjusts the "usable window" of the * internal array forward by one position (effectively making what was the * second element the first, and so on). Repeated activations of this method * (or activation of {@link #discardFrontElements(int)}) will effectively orphan * the storage locations at the beginning of the internal storage array. To * reclaim this storage, each time one of these methods is activated, the size * of the internal storage array is compared to the number of addressable * elements (the <code>numElements</code> property) and if the difference * is too large, the internal array is contracted to size * <code>numElements + 1.</code> The determination of when the internal * storage array is "too large" depends on the <code>expansionMode</code> and * <code>contractionFactor</code> properties. If the <code>expansionMode</code> * is <code>MULTIPLICATIVE_MODE</code>, contraction is triggered when the * ratio between storage array length and <code>numElements</code> exceeds * <code>contractionFactor.</code> If the <code>expansionMode</code> * is <code>ADDITIVE_MODE,</code> the number of excess storage locations * is compared to <code>contractionFactor.</code> * </p> * <p> * To avoid cycles of expansions and contractions, the * <code>expansionFactor</code> must not exceed the * <code>contractionFactor.</code> Constructors and mutators for both of these * properties enforce this requirement, throwing IllegalArgumentException if it * is violated. * </p> * * @version $Revision: 811833 $ $Date: 2009-09-06 09:27:50 -0700 (Sun, 06 Sep 2009) $ */ public class ResizableDoubleArray implements DoubleArray, Serializable { /** * additive expansion mode */ public static final int ADDITIVE_MODE = 1; /** * multiplicative expansion mode */ public static final int MULTIPLICATIVE_MODE = 0; /** * Serializable version identifier */ private static final long serialVersionUID = -1235529955529426875L; /** * The contraction criteria determines when the internal array will be * contracted to fit the number of elements contained in the element * array + 1. */ protected float contractionCriteria = 2.5f; /** * The expansion factor of the array. When the array needs to be expanded, * the new array size will be * <code>internalArray.length * expansionFactor</code> * if <code>expansionMode</code> is set to MULTIPLICATIVE_MODE, or * <code>internalArray.length + expansionFactor</code> if * <code>expansionMode</code> is set to ADDITIVE_MODE. */ protected float expansionFactor = 2.0f; /** * Determines whether array expansion by <code>expansionFactor</code> * is additive or multiplicative. */ protected int expansionMode = MULTIPLICATIVE_MODE; /** * The initial capacity of the array. Initial capacity is not exposed as a * property as it is only meaningful when passed to a constructor. */ protected int initialCapacity = 16; /** * The internal storage array. */ protected double[] internalArray; /** * The number of addressable elements in the array. Note that this * has nothing to do with the length of the internal storage array. */ protected int numElements; /** * The position of the first addressable element in the internal storage * array. The addressable elements in the array are <code> * internalArray[startIndex],...,internalArray[startIndex + numElements -1] * </code> */ protected int startIndex; /** * Create a ResizableArray with default properties. * <ul> * <li><code>initialCapacity = 16</code></li> * <li><code>expansionMode = MULTIPLICATIVE_MODE</code></li> * <li><code>expansionFactor = 2.5</code></li> * <li><code>contractionFactor = 2.0</code></li> * </ul> */ public ResizableDoubleArray() { internalArray = new double[initialCapacity]; } /** * Create a ResizableArray with the specified initial capacity. Other * properties take default values: * <ul> * <li><code>expansionMode = MULTIPLICATIVE_MODE</code></li> * <li><code>expansionFactor = 2.5</code></li> * <li><code>contractionFactor = 2.0</code></li> * </ul> * * @param initialCapacity The initial size of the internal storage array * @throws IllegalArgumentException if initialCapacity is not > 0 */ public ResizableDoubleArray(final int initialCapacity) { setInitialCapacity(initialCapacity); internalArray = new double[this.initialCapacity]; } /** * <p> * Create a ResizableArray with the specified initial capacity * and expansion factor. The remaining properties take default * values: * <ul> * <li><code>expansionMode = MULTIPLICATIVE_MODE</code></li> * <li><code>contractionFactor = 0.5 + expansionFactor</code></li> * </ul></p> * <p> * Throws IllegalArgumentException if the following conditions are * not met: * <ul> * <li><code>initialCapacity > 0</code></li> * <li><code>expansionFactor > 1</code></li> * </ul></p> * * @param initialCapacity The initial size of the internal storage array * @param expansionFactor the array will be expanded based on this * parameter * @throws IllegalArgumentException if parameters are not valid */ public ResizableDoubleArray(final int initialCapacity, final float expansionFactor) { this.expansionFactor = expansionFactor; setInitialCapacity(initialCapacity); internalArray = new double[initialCapacity]; setContractionCriteria(expansionFactor + 0.5f); } /** * <p> * Create a ResizableArray with the specified initialCapacity, * expansionFactor, and contractionCriteria. The <code>expansionMode</code> * will default to <code>MULTIPLICATIVE_MODE.</code></p> * <p> * Throws IllegalArgumentException if the following conditions are * not met: * <ul> * <li><code>initialCapacity > 0</code></li> * <li><code>expansionFactor > 1</code></li> * <li><code>contractionFactor >= expansionFactor</code></li> * </ul></p> * * @param initialCapacity The initial size of the internal storage array * @param expansionFactor the array will be expanded based on this * parameter * @param contractionCriteria The contraction Criteria. * @throws IllegalArgumentException if parameters are not valid */ public ResizableDoubleArray(final int initialCapacity, final float expansionFactor, final float contractionCriteria) { this.expansionFactor = expansionFactor; setContractionCriteria(contractionCriteria); setInitialCapacity(initialCapacity); internalArray = new double[initialCapacity]; } /** * <p> * Create a ResizableArray with the specified properties.</p> * <p> * Throws IllegalArgumentException if the following conditions are * not met: * <ul> * <li><code>initialCapacity > 0</code></li> * <li><code>expansionFactor > 1</code></li> * <li><code>contractionFactor >= expansionFactor</code></li> * <li><code>expansionMode in {MULTIPLICATIVE_MODE, ADDITIVE_MODE}</code> * </li> * </ul></p> * * @param initialCapacity the initial size of the internal storage array * @param expansionFactor the array will be expanded based on this * parameter * @param contractionCriteria the contraction Criteria * @param expansionMode the expansion mode * @throws IllegalArgumentException if parameters are not valid */ public ResizableDoubleArray(final int initialCapacity, final float expansionFactor, final float contractionCriteria, final int expansionMode) { this.expansionFactor = expansionFactor; setContractionCriteria(contractionCriteria); setInitialCapacity(initialCapacity); setExpansionMode(expansionMode); internalArray = new double[initialCapacity]; } /** * Copy constructor. Creates a new ResizableDoubleArray that is a deep, * fresh copy of the original. Needs to acquire synchronization lock * on original. Original may not be null; otherwise a NullPointerException * is thrown. * * @param original array to copy * @since 2.0 */ public ResizableDoubleArray(final ResizableDoubleArray original) { copy(original, this); } /** * Adds an element to the end of this expandable array. * * @param value to be added to end of array */ public synchronized void addElement(final double value) { numElements++; if (startIndex + numElements > internalArray.length) { expand(); } internalArray[startIndex + numElements - 1] = value; if (shouldContract()) { contract(); } } /** * <p> * Adds an element to the end of the array and removes the first * element in the array. Returns the discarded first element. * The effect is similar to a push operation in a FIFO queue. * * <p> * Example: If the array contains the elements 1, 2, 3, 4 (in that order) * and addElementRolling(5) is invoked, the result is an array containing * the entries 2, 3, 4, 5 and the value returned is 1. * * * @param value the value to be added to the array * @return the value which has been discarded or "pushed" out of the array * by this rolling insert */ public synchronized double addElementRolling(final double value) { final double discarded = internalArray[startIndex]; if (startIndex + numElements + 1 > internalArray.length) { expand(); } // Increment the start index startIndex += 1; // Add the new value internalArray[startIndex + numElements - 1] = value; // Check the contraction criteria if (shouldContract()) { contract(); } return discarded; } /** * Substitutes <code>value</code> for the most recently added value. * Returns the value that has been replaced. If the array is empty (i.e. * if {@link #numElements} is zero), a MathRuntimeException is thrown. * * @param value new value to substitute for the most recently added value * @return value that has been replaced in the array * @since 2.0 */ public synchronized double substituteMostRecentElement(final double value) { if (numElements < 1) { throw MathRuntimeException.createArrayIndexOutOfBoundsException( "cannot substitute an element from an empty array"); } final double discarded = internalArray[startIndex + numElements - 1]; internalArray[startIndex + numElements - 1] = value; return discarded; } /** * Checks the expansion factor and the contraction criteria and throws an * IllegalArgumentException if the contractionCriteria is less than the * expansionCriteria * * @param expansion factor to be checked * @param contraction criteria to be checked * @throws IllegalArgumentException if the contractionCriteria is less than * the expansionCriteria. */ protected void checkContractExpand(final float contraction, final float expansion) { if (contraction < expansion) { throw MathRuntimeException.createIllegalArgumentException( "contraction criteria ({0}) smaller than the expansion factor ({1}). This would " + "lead to a never ending loop of expansion and contraction as a newly expanded " + "internal storage array would immediately satisfy the criteria for contraction", contraction, expansion); } if (contraction <= 1.0) { throw MathRuntimeException.createIllegalArgumentException( "contraction criteria smaller than one ({0}). This would lead to a never ending " + "loop of expansion and contraction as an internal storage array length equal " + "to the number of elements would satisfy the contraction criteria.", contraction); } if (expansion <= 1.0) { throw MathRuntimeException.createIllegalArgumentException( "expansion factor smaller than one ({0})", expansion); } } /** * Clear the array, reset the size to the initialCapacity and the number * of elements to zero. */ public synchronized void clear() { numElements = 0; startIndex = 0; internalArray = new double[initialCapacity]; } /** * Contracts the storage array to the (size of the element set) + 1 - to * avoid a zero length array. This function also resets the startIndex to * zero. */ public synchronized void contract() { final double[] tempArray = new double[numElements + 1]; // Copy and swap - copy only the element array from the src array. System.arraycopy(internalArray, startIndex, tempArray, 0, numElements); internalArray = tempArray; // Reset the start index to zero startIndex = 0; } /** * Discards the <code>i<code> initial elements of the array. For example, * if the array contains the elements 1,2,3,4, invoking * <code>discardFrontElements(2)</code> will cause the first two elements * to be discarded, leaving 3,4 in the array. Throws illegalArgumentException * if i exceeds numElements. * * @param i the number of elements to discard from the front of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 */ public synchronized void discardFrontElements(final int i) { discardExtremeElements(i, true); } /** * Discards the <code>i<code> last elements of the array. For example, * if the array contains the elements 1,2,3,4, invoking * <code>discardMostRecentElements(2)</code> will cause the last two elements * to be discarded, leaving 1,2 in the array. Throws illegalArgumentException * if i exceeds numElements. * * @param i the number of elements to discard from the end of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 */ public synchronized void discardMostRecentElements(final int i) { discardExtremeElements(i, false); } /** * Discards the <code>i<code> first or last elements of the array, * depending on the value of <code>front</code>. * For example, if the array contains the elements 1,2,3,4, invoking * <code>discardExtremeElements(2,false)</code> will cause the last two elements * to be discarded, leaving 1,2 in the array. * For example, if the array contains the elements 1,2,3,4, invoking * <code>discardExtremeElements(2,true)</code> will cause the first two elements * to be discarded, leaving 3,4 in the array. * Throws illegalArgumentException * if i exceeds numElements. * * @param i the number of elements to discard from the front/end of the array * @param front true if elements are to be discarded from the front * of the array, false if elements are to be discarded from the end * of the array * @throws IllegalArgumentException if i is greater than numElements. * @since 2.0 */ private synchronized void discardExtremeElements(final int i, final boolean front) { if (i > numElements) { throw MathRuntimeException.createIllegalArgumentException( "cannot discard {0} elements from a {1} elements array", i, numElements); } else if (i < 0) { throw MathRuntimeException.createIllegalArgumentException( "cannot discard a negative number of elements ({0})", i); } else { // "Subtract" this number of discarded from numElements numElements -= i; if (front) { startIndex += i; } } if (shouldContract()) { contract(); } } /** * Expands the internal storage array using the expansion factor. * <p> * if <code>expansionMode</code> is set to MULTIPLICATIVE_MODE, * the new array size will be <code>internalArray.length * expansionFactor.</code> * If <code>expansionMode</code> is set to ADDITIVE_MODE, the length * after expansion will be <code>internalArray.length + expansionFactor</code> * */ protected synchronized void expand() { // notice the use of Math.ceil(), this guarantees that we will always // have an array of at least currentSize + 1. Assume that the // current initial capacity is 1 and the expansion factor // is 1.000000000000000001. The newly calculated size will be // rounded up to 2 after the multiplication is performed. int newSize = 0; if (expansionMode == MULTIPLICATIVE_MODE) { newSize = (int) Math.ceil(internalArray.length * expansionFactor); } else { newSize = internalArray.length + Math.round(expansionFactor); } final double[] tempArray = new double[newSize]; // Copy and swap System.arraycopy(internalArray, 0, tempArray, 0, internalArray.length); internalArray = tempArray; } /** * Expands the internal storage array to the specified size. * * @param size Size of the new internal storage array */ private synchronized void expandTo(final int size) { final double[] tempArray = new double[size]; // Copy and swap System.arraycopy(internalArray, 0, tempArray, 0, internalArray.length); internalArray = tempArray; } /** * The contraction criteria defines when the internal array will contract * to store only the number of elements in the element array. * If the <code>expansionMode</code> is <code>MULTIPLICATIVE_MODE</code>, * contraction is triggered when the ratio between storage array length * and <code>numElements</code> exceeds <code>contractionFactor</code>. * If the <code>expansionMode</code> is <code>ADDITIVE_MODE</code>, the * number of excess storage locations is compared to * <code>contractionFactor.</code> * * @return the contraction criteria used to reclaim memory. */ public float getContractionCriteria() { return contractionCriteria; } /** * Returns the element at the specified index * * @param index index to fetch a value from * @return value stored at the specified index * @throws ArrayIndexOutOfBoundsException if <code>index</code> is less than * zero or is greater than <code>getNumElements() - 1</code>. */ public synchronized double getElement(final int index) { if (index >= numElements) { throw MathRuntimeException.createArrayIndexOutOfBoundsException( "the index specified: {0} is larger than the current maximal index {1}", index, numElements - 1); } else if (index >= 0) { return internalArray[startIndex + index]; } else { throw MathRuntimeException.createArrayIndexOutOfBoundsException( "elements cannot be retrieved from a negative array index {0}", index); } } /** * Returns a double array containing the elements of this * <code>ResizableArray</code>. This method returns a copy, not a * reference to the underlying array, so that changes made to the returned * array have no effect on this <code>ResizableArray.</code> * * @return the double array. */ public synchronized double[] getElements() { final double[] elementArray = new double[numElements]; System.arraycopy(internalArray, startIndex, elementArray, 0, numElements); return elementArray; } /** * The expansion factor controls the size of a new array when an array * needs to be expanded. The <code>expansionMode</code> * determines whether the size of the array is multiplied by the * <code>expansionFactor</code> (MULTIPLICATIVE_MODE) or if * the expansion is additive (ADDITIVE_MODE -- <code>expansionFactor</code> * storage locations added). The default <code>expansionMode</code> is * MULTIPLICATIVE_MODE and the default <code>expansionFactor</code> * is 2.0. * * @return the expansion factor of this expandable double array */ public float getExpansionFactor() { return expansionFactor; } /** * The <code>expansionMode</code> determines whether the internal storage * array grows additively (ADDITIVE_MODE) or multiplicatively * (MULTIPLICATIVE_MODE) when it is expanded. * * @return Returns the expansionMode. */ public int getExpansionMode() { return expansionMode; } /** * Notice the package scope on this method. This method is simply here * for the JUnit test, it allows us check if the expansion is working * properly after a number of expansions. This is not meant to be a part * of the public interface of this class. * * @return the length of the internal storage array. */ synchronized int getInternalLength() { return internalArray.length; } /** * Returns the number of elements currently in the array. Please note * that this is different from the length of the internal storage array. * * @return number of elements */ public synchronized int getNumElements() { return numElements; } /** * Returns the internal storage array. Note that this method returns * a reference to the internal storage array, not a copy, and to correctly * address elements of the array, the <code>startIndex</code> is * required (available via the {@link #start} method). This method should * only be used in cases where copying the internal array is not practical. * The {@link #getElements} method should be used in all other cases. * * @return the internal storage array used by this object * @deprecated replaced by {@link #getInternalValues()} as of 2.0 */ @Deprecated public synchronized double[] getValues() { return internalArray; } /** * Returns the internal storage array. Note that this method returns * a reference to the internal storage array, not a copy, and to correctly * address elements of the array, the <code>startIndex</code> is * required (available via the {@link #start} method). This method should * only be used in cases where copying the internal array is not practical. * The {@link #getElements} method should be used in all other cases. * * @return the internal storage array used by this object * @since 2.0 */ public synchronized double[] getInternalValues() { return internalArray; } /** * Sets the contraction criteria for this ExpandContractDoubleArray. * * @param contractionCriteria contraction criteria */ public void setContractionCriteria(final float contractionCriteria) { checkContractExpand(contractionCriteria, getExpansionFactor()); synchronized (this) { this.contractionCriteria = contractionCriteria; } } /** * Sets the element at the specified index. If the specified index is greater than * <code>getNumElements() - 1</code>, the <code>numElements</code> property * is increased to <code>index +1</code> and additional storage is allocated * (if necessary) for the new element and all (uninitialized) elements * between the new element and the previous end of the array). * * @param index index to store a value in * @param value value to store at the specified index * @throws ArrayIndexOutOfBoundsException if <code>index</code> is less than * zero. */ public synchronized void setElement(final int index, final double value) { if (index < 0) { throw MathRuntimeException.createArrayIndexOutOfBoundsException( "cannot set an element at a negative index {0}", index); } if (index + 1 > numElements) { numElements = index + 1; } if (startIndex + index >= internalArray.length) { expandTo(startIndex + index + 1); } internalArray[startIndex + index] = value; } /** * Sets the expansionFactor. Throws IllegalArgumentException if the * the following conditions are not met: * <ul> * <li><code>expansionFactor > 1</code></li> * <li><code>contractionFactor >= expansionFactor</code></li> * </ul> * * @param expansionFactor the new expansion factor value. * @throws IllegalArgumentException if expansionFactor is <= 1 or greater * than contractionFactor */ public void setExpansionFactor(final float expansionFactor) { checkContractExpand(getContractionCriteria(), expansionFactor); // The check above verifies that the expansion factor is > 1.0; synchronized (this) { this.expansionFactor = expansionFactor; } } /** * Sets the <code>expansionMode</code>. The specified value must be one of * ADDITIVE_MODE, MULTIPLICATIVE_MODE. * * @param expansionMode The expansionMode to set. * @throws IllegalArgumentException if the specified mode value is not valid */ public void setExpansionMode(final int expansionMode) { if (expansionMode != MULTIPLICATIVE_MODE && expansionMode != ADDITIVE_MODE) { throw MathRuntimeException.createIllegalArgumentException( "unsupported expansion mode {0}, supported modes are {1} ({2}) and {3} ({4})", expansionMode, MULTIPLICATIVE_MODE, "MULTIPLICATIVE_MODE", ADDITIVE_MODE, "ADDITIVE_MODE"); } synchronized (this) { this.expansionMode = expansionMode; } } /** * Sets the initial capacity. Should only be invoked by constructors. * * @param initialCapacity of the array * @throws IllegalArgumentException if <code>initialCapacity</code> is not * positive. */ protected void setInitialCapacity(final int initialCapacity) { if (initialCapacity > 0) { synchronized (this) { this.initialCapacity = initialCapacity; } } else { throw MathRuntimeException.createIllegalArgumentException( "initial capacity ({0}) is not positive", initialCapacity); } } /** * This function allows you to control the number of elements contained * in this array, and can be used to "throw out" the last n values in an * array. This function will also expand the internal array as needed. * * @param i a new number of elements * @throws IllegalArgumentException if <code>i</code> is negative. */ public synchronized void setNumElements(final int i) { // If index is negative thrown an error if (i < 0) { throw MathRuntimeException.createIllegalArgumentException( "index ({0}) is not positive", i); } // Test the new num elements, check to see if the array needs to be // expanded to accommodate this new number of elements if (startIndex + i > internalArray.length) { expandTo(startIndex + i); } // Set the new number of elements to new value numElements = i; } /** * Returns true if the internal storage array has too many unused * storage positions. * * @return true if array satisfies the contraction criteria */ private synchronized boolean shouldContract() { if (expansionMode == MULTIPLICATIVE_MODE) { return internalArray.length / (float) numElements > contractionCriteria; } else { return internalArray.length - numElements > contractionCriteria; } } /** * Returns the starting index of the internal array. The starting index is * the position of the first addressable element in the internal storage * array. The addressable elements in the array are <code> * internalArray[startIndex],...,internalArray[startIndex + numElements -1] * </code> * * @return starting index */ public synchronized int start() { return startIndex; } /** * <p>Copies source to dest, copying the underlying data, so dest is * a new, independent copy of source. Does not contract before * the copy.</p> * * <p>Obtains synchronization locks on both source and dest * (in that order) before performing the copy.</p> * * <p>Neither source nor dest may be null; otherwise a NullPointerException * is thrown</p> * * @param source ResizableDoubleArray to copy * @param dest ResizableArray to replace with a copy of the source array * @since 2.0 */ public static void copy(final ResizableDoubleArray source, final ResizableDoubleArray dest) { synchronized (source) { synchronized (dest) { dest.initialCapacity = source.initialCapacity; dest.contractionCriteria = source.contractionCriteria; dest.expansionFactor = source.expansionFactor; dest.expansionMode = source.expansionMode; dest.internalArray = new double[source.internalArray.length]; System.arraycopy(source.internalArray, 0, dest.internalArray, 0, dest.internalArray.length); dest.numElements = source.numElements; dest.startIndex = source.startIndex; } } } /** * Returns a copy of the ResizableDoubleArray. Does not contract before * the copy, so the returned object is an exact copy of this. * * @return a new ResizableDoubleArray with the same data and configuration * properties as this * @since 2.0 */ public synchronized ResizableDoubleArray copy() { final ResizableDoubleArray result = new ResizableDoubleArray(); copy(this, result); return result; } /** * Returns true iff object is a ResizableDoubleArray with the same properties * as this and an identical internal storage array. * * @param object object to be compared for equality with this * @return true iff object is a ResizableDoubleArray with the same data and * properties as this * @since 2.0 */ @Override public boolean equals(final Object object) { if (object == this) { return true; } if (!(object instanceof ResizableDoubleArray)) { return false; } synchronized (this) { synchronized (object) { boolean result = true; final ResizableDoubleArray other = (ResizableDoubleArray) object; result = result && other.initialCapacity == initialCapacity; result = result && other.contractionCriteria == contractionCriteria; result = result && other.expansionFactor == expansionFactor; result = result && other.expansionMode == expansionMode; result = result && other.numElements == numElements; result = result && other.startIndex == startIndex; if (!result) { return false; } else { return Arrays.equals(internalArray, other.internalArray); } } } } /** * Returns a hash code consistent with equals. * * @return hash code representing this ResizableDoubleArray * @since 2.0 */ @Override public synchronized int hashCode() { final int[] hashData = new int[7]; hashData[0] = new Float(expansionFactor).hashCode(); hashData[1] = new Float(contractionCriteria).hashCode(); hashData[2] = expansionMode; hashData[3] = Arrays.hashCode(internalArray); hashData[4] = initialCapacity; hashData[5] = numElements; hashData[6] = startIndex; return Arrays.hashCode(hashData); } }
google/s2-geometry-library-java
35,730
tests/tests/com/google/common/geometry/S2FurthestEdgeQueryTest.java
/* * Copyright 2022 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.common.geometry; import static com.google.common.geometry.S2Projections.MAX_DIAG; import static com.google.common.geometry.S2TextFormat.makeIndexOrDie; import static com.google.common.geometry.S2TextFormat.makePointOrDie; import static com.google.common.geometry.S2TextFormat.parsePointsOrDie; import static java.lang.Math.min; import static java.lang.Math.pow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.geometry.BestEdgesTestUtils.MinOrMax; import com.google.common.geometry.S2BestEdgesQueryBase.Result; import com.google.common.geometry.S2FurthestEdgeQuery.Query; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests for S2FurthestEdgeQuery and the underlying S2BestEdgesQueryBase which supplies the * interesting parts of the implementation. */ @RunWith(JUnit4.class) public final class S2FurthestEdgeQueryTest extends GeometryTestCase { /** * For the given S2FurthestEdgeQuery.Target and S2ShapeIndex, visits and returns up to maxShapes * S2Shapes from the index containing a point antipodal to a connected component of the target. */ public static Set<S2Shape> getAntipodalShapes( S2FurthestEdgeQuery.Target<S1ChordAngle> target, S2ShapeIndex index, int maxShapes) { S2FurthestEdgeQuery.Query furthestEdgeQuery = S2FurthestEdgeQuery.builder().build(index); // Visits shapes that contain a point antipodal to a connected component of the target. final Set<S2Shape> visitedShapes = new HashSet<>(); furthestEdgeQuery.visitAntipodalShapes( target, shapeId -> { visitedShapes.add(index.getShapes().get(shapeId)); return visitedShapes.size() < maxShapes; }); assertLessOrEqual(visitedShapes.size(), maxShapes); return visitedShapes; } @Test public void testNoEdges() { S2ShapeIndex index = makeIndexOrDie("# #"); Query query = S2FurthestEdgeQuery.builder().build(index); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(new S2Point(1, 0, 0)); Optional<Result<S1ChordAngle>> result = query.findFurthestEdge(target); assertFalse(result.isPresent()); } @Test public void testOptionsNotModified() { // Tests that findFurthestEdge(), getDistance(), and isDistanceGreater() do not modify // query.options(), even though all of these methods have their own specific options // requirements. S2FurthestEdgeQuery.Builder builder = S2FurthestEdgeQuery.builder() .setMinDistance(S1ChordAngle.fromDegrees(1)) .setMaxError(S1ChordAngle.fromDegrees(0.001)) .setMaxResults(3); // First, verify that the builder is storing the expected values. assertEquals(3, builder.maxResults()); assertExactly( S1ChordAngle.fromDegrees(1).getLength2(), builder.minDistance().getLength2()); assertExactly( S1ChordAngle.fromDegrees(0.001).getLength2(), builder.maxError().getLength2()); S2ShapeIndex index = makeIndexOrDie("0:1 | 0:2 | 0:3 # #"); Query query = builder.build(index); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(makePointOrDie("0:4")); assertEquals(0, query.findFurthestEdge(target).get().edgeId()); assertDoubleNear(3.0, query.getDistance(target).degrees(), 1e-15); assertTrue(query.isDistanceGreater(target, S1ChordAngle.fromDegrees(1.5))); // Verify that none of the query options were modified. assertEquals(builder.maxResults(), query.options().maxResults()); assertEquals(builder.minDistance(), query.options().distanceLimit()); assertEquals(builder.maxError(), query.options().maxError()); } /** Verifies that visitAntipodalShapes visits the correct shapes for a point target. */ @Test public void testVisitAntipodalShapesForPointTarget() { // Builds an index containing 1 point, 1 edge, and 3 polygons, each with a single triangular // loop. Only shapes 2 and 4 (the first and third polygons) are at maximum distance to the // target. // (Note that the S2ContainsPointQuery vertex model is SEMI_OPEN, therefore no point or edge // contains anything, not even edges containing their endpoints.) S2ShapeIndex index = makeIndexOrDie("1:1 # 1:1, 2:2 # 0:0, 0:3, 3:0 | 6:6, 6:9, 9:6 | 0:0, 0:4, 4:0"); S2Point p = makePointOrDie("1:1"); // Make the target antipodal to 1:1 so the polygons at max distance are those that contain 1:1. S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(p.neg()); // Visit up to one shape at best (maximum) distance from the target. Either shape 2 or 4 should // be the only one. Set<S2Shape> shapeSet = getAntipodalShapes(target, index, 1); assertEquals(1, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); // If up to 5 antipodal shapes may be visited, exactly shapes 2 and 4 actually should be. shapeSet = getAntipodalShapes(target, index, 5); assertEquals(2, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); } /** Verifies that visitAntipodalShapes visits the correct shapes for an edge target. */ @Test public void testVisitAntipodalShapesForEdgeTarget() { // Builds an index containing 1 point, 1 edge, and 3 polygons, each with a single triangular // loop. Only shapes 2 and 4 (the first and third polygons) should be antipodal to the target. S2ShapeIndex index = makeIndexOrDie("1:1 # 1:1, 2:2 # 0:0, 0:3, 3:0 | 6:6, 6:9, 9:6 | 0:0, 0:4, 4:0"); // Make the target antipodal to the 1:1,2:1 edge, so the polygons at max distance are the // two triangles above. List<S2Point> edge = parsePointsOrDie("1:2, 2:1"); S2FurthestEdgeQuery.EdgeTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.EdgeTarget<>(edge.get(0).neg(), edge.get(1).neg()); // Visit up to one antipodal shape. Either shape 2 or 4 should be the only one. Set<S2Shape> shapeSet = getAntipodalShapes(target, index, 1); assertEquals(1, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); // If up to 5 antipodal shapes may be visited, exactly shapes 2 and 4 actually should be. shapeSet = getAntipodalShapes(target, index, 5); assertEquals(2, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); } /** Verifies that visitAntipodalShapes visits the correct shapes for cell target. */ @Test public void testVisitAntipodalShapesForCellTarget() { // Builds an index containing 1 point, 1 edge, and 3 polygons, each with a single triangular // loop. Only shapes 2 and 4 (the first and third polygons) should contain the very small (leaf) // target cell near the antipode of 1:1. S2ShapeIndex index = makeIndexOrDie("1:1 # 1:1, 2:2 # 0:0, 0:3, 3:0 | 6:6, 6:9, 9:6 | -1:-1, -1:5, 5:-1"); S2CellId cellId1 = S2CellId.fromPoint(makePointOrDie("1:1").neg()); S2FurthestEdgeQuery.CellTarget<S1ChordAngle> target1 = new S2FurthestEdgeQuery.CellTarget<>(new S2Cell(cellId1)); // Visit up to one antipodal shape. Either shape 2 or 4 should be the only one. Set<S2Shape> shapeSet = getAntipodalShapes(target1, index, 1); assertEquals(1, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); // If up to 5 antipodal shapes may be visited, only shapes 2 and 4 actually should be. shapeSet = getAntipodalShapes(target1, index, 5); assertEquals(2, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); // For a larger cell that properly contains the antipodal reflection of one or more index cells, // all shapes that intersect the first such cell in S2CellId order are returned. In the test // below, this happens to again be the first and third polygons, whose shape ids are 2 and 4. S2CellId cellId2 = cellId1.parent(5); S2FurthestEdgeQuery.CellTarget<S1ChordAngle> target2 = new S2FurthestEdgeQuery.CellTarget<>(new S2Cell(cellId2)); shapeSet = getAntipodalShapes(target2, index, 5); assertEquals(2, shapeSet.size()); assertTrue( ImmutableSet.of(index.getShapes().get(2), index.getShapes().get(4)).containsAll(shapeSet)); } // In furthest edge queries, the following distance computation is used when updating max // distances. S1ChordAngle getMaxDistanceToEdge(S2Point x, S2Point y0, S2Point y1) { return S2EdgeUtil.updateMaxDistance(x, y0, y1, S1ChordAngle.ZERO); } @Test public void testDistanceEqualToLimit() { // Tests the behavior of isDistanceGreater, isDistanceGreaterOrEqual, and // isConservativeDistanceGreaterOrEqual (and the corresponding Options) when the distance to the // target exactly equals the chosen limit. S2Point p0 = makePointOrDie("23:12"); S2Point p1 = makePointOrDie("47:11"); S2ShapeIndex index = new S2ShapeIndex(); index.add(S2Point.Shape.singleton(p0)); Query query = S2FurthestEdgeQuery.builder().build(index); // Start with antipodal points and a maximum (180 degrees) distance. S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target0 = new S2FurthestEdgeQuery.PointTarget<>(p0.neg()); S1ChordAngle distMax = S1ChordAngle.STRAIGHT; assertFalse(query.isDistanceGreater(target0, distMax)); assertTrue(query.isDistanceGreaterOrEqual(target0, distMax)); assertTrue(query.isConservativeDistanceGreaterOrEqual(target0, distMax)); // Now try two points separated by a non-maximal distance. S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target1 = new S2FurthestEdgeQuery.PointTarget<>(p1.neg()); S1ChordAngle dist1 = getMaxDistanceToEdge(p0, p1.neg(), p1.neg()); assertFalse("dist1 = " + dist1, query.isDistanceGreater(target1, dist1)); assertTrue(query.isDistanceGreaterOrEqual(target1, dist1)); assertTrue(query.isConservativeDistanceGreaterOrEqual(target1, dist1)); } @SuppressWarnings("FloatingPointLiteralPrecision") @Test public void testTrueDistanceGreaterThanS1ChordAngleDistance() { // Tests that isConservativeDistanceGreaterOrEqual returns points where the true distance is // slightly greater than the one computed by S1ChordAngle. // // The points below had the worst error from among 1x10^6 random pairs. S2Point p0 = new S2Point(0.72362949088190598, -0.39019820403414807, -0.56930283812266336); S2Point p1 = new S2Point(0.54383822931548842, 0.758981734255934404, 0.35803171284238039); // Verify that the S1ChordAngle distance is ~3 ulps greater than the true distance. S1ChordAngle dist1 = getMaxDistanceToEdge(p0, p1, p1); S1ChordAngle limit = dist1.successor().successor().successor(); assertGreaterThan(S2Predicates.compareDistance(p0, p1, limit.getLength2()), 0); // Verify that isConservativeDistanceGreaterOrEqual() still returns "p1". S2ShapeIndex index = new S2ShapeIndex(); index.add(S2Point.Shape.singleton(p0)); Query query = S2FurthestEdgeQuery.builder().build(index); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target1 = new S2FurthestEdgeQuery.PointTarget<>(p1); assertFalse(query.isDistanceGreater(target1, limit)); assertFalse(query.isDistanceGreaterOrEqual(target1, limit)); assertTrue(query.isConservativeDistanceGreaterOrEqual(target1, limit)); } @Test public void testAntipodalPointInsideIndexedPolygon() { // Tests a target point antipodal to the interior of an indexed polygon. // (The index also includes a polyline loop with no interior.) S2ShapeIndex index = makeIndexOrDie("# 0:0, 0:5, 5:5, 5:0 # 0:10, 0:15, 5:15, 5:10"); S2FurthestEdgeQuery.Builder builder = S2FurthestEdgeQuery.builder() .setMinDistance(S1Angle.degrees(178)) .setIncludeInteriors(true); // First check that with includeInteriors set to true, the distance is maximum (180 degrees). Query query = builder.build(index); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(makePointOrDie("2:12").neg()); List<Result<S1ChordAngle>> results = query.findFurthestEdges(target); assertGreaterThan(results.size(), 0); assertEquals(S1ChordAngle.STRAIGHT, results.get(0).distance()); assertEquals(1, results.get(0).shapeId()); assertEquals(-1, results.get(0).edgeId()); // Next check that with includeInteriors set to false, the distance is less than 180 for the // same target and index. Query query2 = query.toBuilder().setIncludeInteriors(false).build(index); results = query2.findFurthestEdges(target); assertGreaterThan(results.size(), 0); assertLessOrEqual(results.get(0).distance(), S1ChordAngle.STRAIGHT); // The same polygon shape, with id 1. assertEquals(1, results.get(0).shapeId()); // Found a specific edge, so id should be positive. assertGreaterThan(results.get(0).edgeId(), 0); } @Test public void testAntipodalPointOutsideIndexedPolygon() { // Tests a target point antipodal to the interior of a polyline loop with no interior. The index // also includes a polygon almost antipodal to the target, but with all edges closer than the // minDistance threshold. S2ShapeIndex index = makeIndexOrDie("# 0:0, 0:5, 5:5, 5:0 # 0:10, 0:15, 5:15, 5:10"); S2FurthestEdgeQuery.Builder builder = S2FurthestEdgeQuery.builder() .setMinDistance(S1Angle.degrees(179)) .setIncludeInteriors(true); Query query = builder.build(index); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(makePointOrDie("2:2").neg()); List<Result<S1ChordAngle>> results = query.findFurthestEdges(target); assertEquals(0, results.size()); } @Test public void testTargetPolygonContainingIndexedPoints() { // Two points are contained within a target polyline loop (no interior) and two points are // contained within a target polygon. S2ShapeIndex index = makeIndexOrDie("2:2 | 4:4 | 1:11 | 3:12 # #"); Query query = S2FurthestEdgeQuery.builder().setUseBruteForce(false).build(index); S2ShapeIndex targetIndex = makeIndexOrDie("# 0:0, 0:5, 5:5, 5:0 # 0:10, 0:15, 5:15, 5:10"); S2FurthestEdgeQuery.ShapeIndexTarget<S1ChordAngle> target = S2FurthestEdgeQuery.createShapeIndexTarget(targetIndex); target.setIncludeInteriors(true); List<Result<S1ChordAngle>> results1 = query.findFurthestEdges(target); // All points should be returned since we did not specify maxResults. assertEquals(4, results1.size()); assertGreaterThan(results1.get(0).distance(), S1ChordAngle.ZERO); assertEquals(0, results1.get(0).shapeId()); assertEquals(0, results1.get(0).edgeId()); // 2:2 (to 5:15) assertGreaterThan(results1.get(1).distance(), S1ChordAngle.ZERO); assertEquals(0, results1.get(1).shapeId()); assertEquals(3, results1.get(1).edgeId()); // 3:12 (to 0:0) } @Test public void testAntipodalPolygonContainingIndexedPoints() { // Two antipodal points are contained within a polyline loop (no interior) // and two antipodal points are contained within a polygon. List<S2Point> points = parsePointsOrDie("2:2, 3:3, 1:11, 3:13"); S2ShapeIndex index = new S2ShapeIndex(); List<S2Point> antipodalPoints = new ArrayList<>(); for (S2Point p : points) { antipodalPoints.add(p.neg()); } index.add(S2Point.Shape.fromList(antipodalPoints)); // With a minimum distance of 179, only the antipodal points contained by the polygon will be // found, at distance STRAIGHT. Query query = S2FurthestEdgeQuery.builder().setMinDistance(S1Angle.degrees(179)).build(index); S2ShapeIndex targetIndex = makeIndexOrDie("# 0:0, 0:5, 5:5, 5:0 # 0:10, 0:15, 5:15, 5:10"); S2FurthestEdgeQuery.ShapeIndexTarget<S1ChordAngle> target = S2FurthestEdgeQuery.createShapeIndexTarget(targetIndex); target.setIncludeInteriors(true); List<Result<S1ChordAngle>> results = query.findFurthestEdges(target); assertEquals(2, results.size()); assertEquals(S1ChordAngle.STRAIGHT, results.get(0).distance()); // The two points could be returned in either order. boolean foundShape0Edge2 = false; boolean foundShape0Edge3 = false; for (Result<S1ChordAngle> result : results) { assertEquals(0, result.shapeId()); assertEquals(S1ChordAngle.STRAIGHT, result.distance()); if (result.edgeId() == 2) { // 1:11 assertFalse(foundShape0Edge2); foundShape0Edge2 = true; } if (result.edgeId() == 3) { // 3:13 assertFalse(foundShape0Edge3); foundShape0Edge3 = true; } } assertTrue(foundShape0Edge2); assertTrue(foundShape0Edge3); } @Test public void testEmptyPolygonTarget() { // Verifies that distances are measured correctly to empty polygon targets. S2ShapeIndex emptyPolygonIndex = makeIndexOrDie("# # empty"); S2ShapeIndex fullPolygonIndex = makeIndexOrDie("# # full"); S2FurthestEdgeQuery.ShapeIndexTarget<S1ChordAngle> emptyPolygonTarget = S2FurthestEdgeQuery.createShapeIndexTarget(emptyPolygonIndex); emptyPolygonTarget.setIncludeInteriors(true); Query pointIndexQuery = S2FurthestEdgeQuery.builder().build(makeIndexOrDie("1:1 # #")); assertEquals(S1ChordAngle.NEGATIVE, pointIndexQuery.getDistance(emptyPolygonTarget)); Query emptyIndexQuery = S2FurthestEdgeQuery.builder().build(emptyPolygonIndex); assertEquals(S1ChordAngle.NEGATIVE, emptyIndexQuery.getDistance(emptyPolygonTarget)); Query fullIndexQuery = S2FurthestEdgeQuery.builder().setIncludeInteriors(true).build(fullPolygonIndex); assertEquals(S1ChordAngle.NEGATIVE, fullIndexQuery.getDistance(emptyPolygonTarget)); } @Test public void testFullLaxPolygonTarget() { // Verifies that distances are measured correctly to full LaxPolygon targets. S2ShapeIndex emptyPolygonIndex = makeIndexOrDie("# # empty"); S2ShapeIndex pointIndex = makeIndexOrDie("1:1 # #"); S2ShapeIndex fullPolygonIndex = makeIndexOrDie("# # full"); S2FurthestEdgeQuery.ShapeIndexTarget<S1ChordAngle> target = S2FurthestEdgeQuery.createShapeIndexTarget(fullPolygonIndex); target.setIncludeInteriors(true); Query emptyQuery = S2FurthestEdgeQuery.builder().build(emptyPolygonIndex); assertEquals(S1ChordAngle.NEGATIVE, emptyQuery.getDistance(target)); Query pointQuery = S2FurthestEdgeQuery.builder().build(pointIndex); assertEquals(S1ChordAngle.STRAIGHT, pointQuery.getDistance(target)); Query fullQuery = S2FurthestEdgeQuery.builder().setIncludeInteriors(true).build(fullPolygonIndex); assertEquals(S1ChordAngle.STRAIGHT, fullQuery.getDistance(target)); } ////////////////////////////////////////////////////////////////////////////// // General query testing by comparing with brute force method. ////////////////////////////////////////////////////////////////////////////// // The approximate radius of S2Cap from which query edges are chosen. static S1Angle kTestCapRadius = kmToAngle(10); // Use "query" to find the furthest edge(s) to the given target. Verify that the results satisfy // the search criteria. void getFurthestEdges( S2FurthestEdgeQuery.Target<S1ChordAngle> target, Query query, List<Result<S1ChordAngle>> edges) { // For half of the tests, have the query return a list of results. For the other half of // tests, use the visitor, although this visitor just puts new Results into the list for // verification anyway. if (data.oneIn(2)) { edges.addAll(query.findFurthestEdges(target)); } else { query.findFurthestEdges(target, (distance, shapeId, edgeId) -> edges.add(new Result<>(distance, shapeId, edgeId))); } assertLessOrEqual(edges.size(), query.options().maxResults()); if (query.options().distanceLimit().isNegative()) { int minExpected = min(query.options().maxResults(), S2ShapeUtil.countEdges(query.index())); if (!query.options().includeInteriors()) { // We can predict exactly how many edges should be returned. assertEquals(minExpected, edges.size()); } else { // All edges should be returned, and possibly some shape interiors. assertLessOrEqual(minExpected, edges.size()); } } for (Result<S1ChordAngle> edge : edges) { // Check that the edge satisfies the minDistance() condition. assertGreaterOrEqual(edge.distance(), query.options().distanceLimit()); } } void testFindFurthestEdges( S2ShapeIndex index, S2FurthestEdgeQuery.Target<S1ChordAngle> target, S2FurthestEdgeQuery.Builder queryBuilder) { List<Result<S1ChordAngle>> bruteForceResults = new ArrayList<>(); List<Result<S1ChordAngle>> optimizedResults = new ArrayList<>(); queryBuilder.setUseBruteForce(true); S2FurthestEdgeQuery.Query bruteForceQuery = queryBuilder.build(index); getFurthestEdges(target, bruteForceQuery, bruteForceResults); queryBuilder.setUseBruteForce(true); S2FurthestEdgeQuery.Query optimizedQuery = queryBuilder.build(index); getFurthestEdges(target, optimizedQuery, optimizedResults); assertTrue(BestEdgesTestUtils.resultsAreEquivalent( MinOrMax.MAX, bruteForceResults, optimizedResults, queryBuilder.maxResults(), queryBuilder.distanceLimit(), queryBuilder.maxError())); if (bruteForceResults.isEmpty()) { return; } // Note that when options.maxError() > 0, expected.get(0).distance may not be the maximum // distance. It is never smaller by more than maxError(), but the actual value also depends on // maxResults(). // // Here we verify that getDistance() and isDistanceGreater() return results that are consistent // with the maxError() setting. S1ChordAngle maxError = queryBuilder.maxError(); // The distance of the truly furthest result. S1ChordAngle bruteForceMaxDistance = bruteForceResults.get(0).distance(); // The closest acceptable result distance, if using maxError. S1ChordAngle lowerBound = S1ChordAngle.sub(bruteForceMaxDistance, maxError); // isDistanceGreater may not return a distance S1ChordAngle upperBound = S1ChordAngle.add(bruteForceMaxDistance, maxError); // getDistance() is permitted to underestimate by as much as maxError, but no more. assertGreaterOrEqual(optimizedQuery.getDistance(target), lowerBound); // Test isDistanceGreater(). assertFalse(optimizedQuery.isDistanceGreater(target, upperBound)); assertTrue(optimizedQuery.isDistanceGreater(target, bruteForceMaxDistance.predecessor())); assertTrue(optimizedQuery.isConservativeDistanceGreaterOrEqual(target, bruteForceMaxDistance)); } /** * Puts shape A in a shape index, edge B in an edge target, and uses a FurthestEdge query to get * the maximum distance between them, after setting 'includeInteriors' for shape A on the query. * Compares the distance to "expectedDistanceRadians". */ private void checkShapeToEdgeMaxDistance( // TODO(user): Port checkShapeToEdgeMaxDistance and the unit tests that use it to C++. S2Shape a, boolean includeInteriors, S2Point b0, S2Point b1, double expectedDistanceRadians) { b0 = b0.normalize(); b1 = b1.normalize(); S2ShapeIndex index = new S2ShapeIndex(); index.add(a); S2FurthestEdgeQuery.EdgeTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.EdgeTarget<>(b0, b1); // Get the single furthest edge. S2FurthestEdgeQuery.Builder builder = S2FurthestEdgeQuery.builder(); builder.setIncludeInteriors(includeInteriors); Query query = builder.build(index); Optional<Result<S1ChordAngle>> opt = query.findFurthestEdge(target); assertTrue(opt.isPresent()); Result<S1ChordAngle> result = opt.get(); // Get the indexed edge that's farthest from the target. S2Shape.MutableEdge edge = new S2Shape.MutableEdge(); index.getShapes().get(result.shapeId()).getEdge(result.edgeId(), edge); assertEquals("Furthest Indexed Edge from target is " + edge.toDegreesString(), expectedDistanceRadians, result.distance().radians(), 1e-15); } /** * Puts edge A in a shape index, edge B in an edge target, and uses a FurthestEdge query to get * the maximum distance between them. Compares to "expectedDistanceRadians". */ private void checkEdgePairMaxDistance( S2Point a0, S2Point a1, S2Point b0, S2Point b1, double expectedDistanceRadians) { checkShapeToEdgeMaxDistance( new S2Edge(a0.normalize(), a1.normalize()), false, b0, b1, expectedDistanceRadians); } /** * Exactly the same test cases as {@link S2EdgeUtilTest#testEdgePairMaxDistanceSimple()} but using * FurthestEdgeQuery. This demonstrates that for simple edge-to-edge queries, the maximum distance * between the index and the target is the maximum distance between the edges. */ @Test public void testFurthestEdgeDistanceEdgePairs() { // Some test points. S2Point center = ll(12, 12); S2Point north = ll(13, 12); S2Point south = ll(11, 12); S2Point east = ll(12, 13); S2Point west = ll(12, 11); S2Point nw = ll(13, 11); S2Point sw = ll(11, 11); S2Point ss = ll(10, 12); // Further south // Edges with a common endpoint, where the maximum distance is between the other endpoints: // Straight line north-south checkEdgePairMaxDistance(north, center, center, south, north.angle(south)); // Straight line east-west checkEdgePairMaxDistance(east, center, center, west, east.angle(west)); // 90 degree turn north to west checkEdgePairMaxDistance(north, center, center, west, north.angle(west)); // Lines that cross: // 90 degree crossing at 'center' checkEdgePairMaxDistance(north, south, east, west, south.angle(west)); // Acute angle crossing at the midpoint between "west" and "center". checkEdgePairMaxDistance(north, sw, south, nw, south.angle(north)); // Lines that don't cross. Max distance is between the most distant endpoints. checkEdgePairMaxDistance(north, nw, south, ss, ss.angle(nw)); } /** Tests simple cases of maximum distance from an edge to a polygon. */ @Test public void testFurthestEdgeDistanceEdgeToPolygon() { S2Point center = ll(12, 12); // Four points around the center S2Point ne = ll(13, 13); S2Point nw = ll(13, 11); S2Point sw = ll(11, 11); S2Point se = ll(11, 13); // A test square, two degrees on a side, centered at 'center'. (The interior of the polygon is // on the left when walking the vertices in the given order). S2LaxPolygonShape square = S2LaxPolygonShape.fromLoop(ImmutableList.of(ne, nw, sw, se)); // The same square, but reversed, so representing the sphere with a square hole cut out of it. S2LaxPolygonShape hole = S2LaxPolygonShape.fromLoop(ImmutableList.of(se, sw, nw, ne)); // A point just inside the square, 0.1 degrees from the west edge (i.e. (13,11) to (11,11)) S2Point inside = ll(12, 11.1); // Two points outside the square, half a degree to the west and east. S2Point west = ll(12, 10.5); S2Point east = ll(12, 13.5); // Check the maximum distance between the square and an edge inside the square, with one edge // endpoint at the center of the square and one endpoint close to a side of the square. The // maximum distance is from the endpoint near the western edge of the square, to the south east // corner of the square. checkShapeToEdgeMaxDistance(square, false, inside, center, inside.angle(se)); // The edge same inside the square hole has the same maximum distance. checkShapeToEdgeMaxDistance(hole, false, inside, center, inside.angle(se)); // Check the maximum distance between the square and an edge crossing one square edge, with one // edge endpoint half a degree outside the square on the west, and one endpoint close to the // west edge inside the square. The maximum distance is // attained between the outside endpoint at 'west' and the opposite (east) side of the square: // the south east corner specifically. checkShapeToEdgeMaxDistance(square, false, west, inside, west.angle(se)); checkShapeToEdgeMaxDistance(hole, false, west, inside, west.angle(se)); // Check the maximum distance between the square and an edge crossing two edges of the square, // so both endpoints are outside the square. In some intuitive sense, the maximum distance // between the edge and the square is between the center of the edge and a corner of the square, // but that is the point on the edge furthest from ALL points on the square. The query returns // the maximum distance between the edge and ANY point on the square, which is the same as the // previous case: the distance from an edge endpoint and a corner of the square on the opposite // side. checkShapeToEdgeMaxDistance(square, false, east, west, west.angle(se)); // Here, both edge endpoints are inside the polygon, but it makes no difference. checkShapeToEdgeMaxDistance(hole, false, east, west, west.angle(se)); } /** * Does 'numQueries' FurthestEdgeQuery tests. Each test runs a query against a randomly selected * index from one of 'numIndexes' randomly generated ShapeIndexes, each of which contains one * pseudo-random shape generated by the given ShapeFactory. The ShapeFactory is initialized from * the TestDataGenerator's internal Random. For each query, random parameters and a random target * are used, also using the TestDataGenerator's internal Random. * * <p>To obtain repeatable test sequences, callers can use data.setSeed() before calling * testWithShapeFactory(). * * <p>The running time of this test is proportional to (numIndexes + numQueries) * numEdges. * (Note that every query is checked using the brute force algorithm.) */ void testWithShapeFactory( TestDataGenerator.ShapeFactory factory, int numIndexes, int numEdges, int numQueries) { // Build a set of S2ShapeIndexes containing a pseudo-random shape from the provided factory. List<S2Cap> indexCaps = new ArrayList<>(); List<S2ShapeIndex> indexes = new ArrayList<>(); // Test indexes are placed at random locations across the whole sphere. for (int i = 0; i < numIndexes; ++i) { S2Cap cap = S2Cap.fromAxisAngle(data.getRandomPoint(), kTestCapRadius); indexCaps.add(cap); indexes.add(factory.getShape(cap, numEdges)); } for (int i = 0; i < numQueries; ++i) { // Select an index at random. int iIndex = data.uniform(numIndexes); S2Cap indexCap = indexCaps.get(iIndex); S2ShapeIndex index = indexes.get(iIndex); // Choose query points from an area approximately 4x larger than the geometry being tested. S1Angle queryRadius = indexCap.angle().mul(2); // Exercise the opposite-hemisphere code 1/5 of the time. S2Point center = data.oneIn(5) ? indexCap.axis().neg() : indexCap.axis(); S2Cap queryCap = S2Cap.fromAxisAngle(center, queryRadius); S2FurthestEdgeQuery.Builder builder = S2FurthestEdgeQuery.builder(); // Occasionally we don't set any limit on the number of result edges. (This may return all // edges if we also don't set a distance limit.) if (!data.oneIn(5)) { builder.setMaxResults(1 + data.uniform(10)); } // We set a distance limit 2/3 of the time. if (!data.oneIn(3)) { builder.setMinDistance(queryRadius.mul(data.nextDouble())); } if (data.oneIn(2)) { // Choose a maximum error whose logarithm is uniformly distributed over a reasonable range, // except that it is sometimes zero. builder.setMaxError( S1ChordAngle.fromRadians(pow(1e-4, data.nextDouble()) * queryRadius.radians())); } builder.setIncludeInteriors(data.oneIn(2)); int targetType = data.uniform(4); if (targetType == 0) { // Find the edges furthest from a given point. S2Point point = data.samplePoint(queryCap); S2FurthestEdgeQuery.PointTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.PointTarget<>(point); testFindFurthestEdges(index, target, builder); } else if (targetType == 1) { // Find the edges furthest from a given edge. S2Point a = data.samplePoint(queryCap); S2Point b = data.samplePoint(S2Cap.fromAxisAngle(a, queryRadius.mul(pow(1e-4, data.nextDouble())))); S2FurthestEdgeQuery.EdgeTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.EdgeTarget<>(a, b); testFindFurthestEdges(index, target, builder); } else if (targetType == 2) { // Find the edges furthest from a given cell. int minLevel = MAX_DIAG.getMinLevel(queryRadius.radians()); int level = minLevel + data.uniform(S2CellId.MAX_LEVEL - minLevel + 1); S2Point a = data.samplePoint(queryCap); S2CellId targetId = S2CellId.fromPoint(a).parent(level); S2Cell cell = new S2Cell(targetId); S2FurthestEdgeQuery.CellTarget<S1ChordAngle> target = new S2FurthestEdgeQuery.CellTarget<>(cell); testFindFurthestEdges(index, target, builder); } else { assertEquals(3, targetType); // Use another one of the pre-built indexes as the target. int jIndex = data.uniform(numIndexes); S2FurthestEdgeQuery.ShapeIndexTarget<S1ChordAngle> target = S2FurthestEdgeQuery.createShapeIndexTarget(indexes.get(jIndex)); boolean targetIncludeInteriors = data.oneIn(2); target.setIncludeInteriors(targetIncludeInteriors); testFindFurthestEdges(index, target, builder); } } } static int kNumIndexes = 50; static int kNumEdges = 100; static int kNumQueries = 200; @Test public void testCircleEdges() { testWithShapeFactory( data.new RegularLoopShapeFactory(), kNumIndexes, kNumEdges, kNumQueries); } @Test public void testFractalEdges() { testWithShapeFactory( data.new FractalLoopShapeFactory(), kNumIndexes, kNumEdges, kNumQueries); } @Test public void testPointCloudEdges() { testWithShapeFactory( data.new PointCloudShapeFactory(), kNumIndexes, kNumEdges, kNumQueries); } }
googleapis/google-cloud-java
35,341
java-netapp/proto-google-cloud-netapp-v1/src/main/java/com/google/cloud/netapp/v1/CreateVolumeRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/netapp/v1/volume.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.netapp.v1; /** * * * <pre> * Message for creating a Volume * </pre> * * Protobuf type {@code google.cloud.netapp.v1.CreateVolumeRequest} */ public final class CreateVolumeRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.netapp.v1.CreateVolumeRequest) CreateVolumeRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateVolumeRequest.newBuilder() to construct. private CreateVolumeRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateVolumeRequest() { parent_ = ""; volumeId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateVolumeRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_CreateVolumeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_CreateVolumeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.CreateVolumeRequest.class, com.google.cloud.netapp.v1.CreateVolumeRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VOLUME_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object volumeId_ = ""; /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The volumeId. */ @java.lang.Override public java.lang.String getVolumeId() { java.lang.Object ref = volumeId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); volumeId_ = s; return s; } } /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for volumeId. */ @java.lang.Override public com.google.protobuf.ByteString getVolumeIdBytes() { java.lang.Object ref = volumeId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); volumeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VOLUME_FIELD_NUMBER = 3; private com.google.cloud.netapp.v1.Volume volume_; /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the volume field is set. */ @java.lang.Override public boolean hasVolume() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The volume. */ @java.lang.Override public com.google.cloud.netapp.v1.Volume getVolume() { return volume_ == null ? com.google.cloud.netapp.v1.Volume.getDefaultInstance() : volume_; } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.netapp.v1.VolumeOrBuilder getVolumeOrBuilder() { return volume_ == null ? com.google.cloud.netapp.v1.Volume.getDefaultInstance() : volume_; } 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(volumeId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, volumeId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getVolume()); } 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(volumeId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, volumeId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getVolume()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.netapp.v1.CreateVolumeRequest)) { return super.equals(obj); } com.google.cloud.netapp.v1.CreateVolumeRequest other = (com.google.cloud.netapp.v1.CreateVolumeRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getVolumeId().equals(other.getVolumeId())) return false; if (hasVolume() != other.hasVolume()) return false; if (hasVolume()) { if (!getVolume().equals(other.getVolume())) 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) + VOLUME_ID_FIELD_NUMBER; hash = (53 * hash) + getVolumeId().hashCode(); if (hasVolume()) { hash = (37 * hash) + VOLUME_FIELD_NUMBER; hash = (53 * hash) + getVolume().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.CreateVolumeRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.netapp.v1.CreateVolumeRequest 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 creating a Volume * </pre> * * Protobuf type {@code google.cloud.netapp.v1.CreateVolumeRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.netapp.v1.CreateVolumeRequest) com.google.cloud.netapp.v1.CreateVolumeRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_CreateVolumeRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_CreateVolumeRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.CreateVolumeRequest.class, com.google.cloud.netapp.v1.CreateVolumeRequest.Builder.class); } // Construct using com.google.cloud.netapp.v1.CreateVolumeRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getVolumeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; volumeId_ = ""; volume_ = null; if (volumeBuilder_ != null) { volumeBuilder_.dispose(); volumeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_CreateVolumeRequest_descriptor; } @java.lang.Override public com.google.cloud.netapp.v1.CreateVolumeRequest getDefaultInstanceForType() { return com.google.cloud.netapp.v1.CreateVolumeRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.netapp.v1.CreateVolumeRequest build() { com.google.cloud.netapp.v1.CreateVolumeRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.netapp.v1.CreateVolumeRequest buildPartial() { com.google.cloud.netapp.v1.CreateVolumeRequest result = new com.google.cloud.netapp.v1.CreateVolumeRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.netapp.v1.CreateVolumeRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.volumeId_ = volumeId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.volume_ = volumeBuilder_ == null ? volume_ : volumeBuilder_.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.netapp.v1.CreateVolumeRequest) { return mergeFrom((com.google.cloud.netapp.v1.CreateVolumeRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.netapp.v1.CreateVolumeRequest other) { if (other == com.google.cloud.netapp.v1.CreateVolumeRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getVolumeId().isEmpty()) { volumeId_ = other.volumeId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasVolume()) { mergeVolume(other.getVolume()); } 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: { volumeId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getVolumeFieldBuilder().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. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Value for parent. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object volumeId_ = ""; /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The volumeId. */ public java.lang.String getVolumeId() { java.lang.Object ref = volumeId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); volumeId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for volumeId. */ public com.google.protobuf.ByteString getVolumeIdBytes() { java.lang.Object ref = volumeId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); volumeId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The volumeId to set. * @return This builder for chaining. */ public Builder setVolumeId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } volumeId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearVolumeId() { volumeId_ = getDefaultInstance().getVolumeId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Id of the requesting volume. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a number, * and a 63 character maximum. * </pre> * * <code>string volume_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for volumeId to set. * @return This builder for chaining. */ public Builder setVolumeIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); volumeId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.netapp.v1.Volume volume_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.Volume, com.google.cloud.netapp.v1.Volume.Builder, com.google.cloud.netapp.v1.VolumeOrBuilder> volumeBuilder_; /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the volume field is set. */ public boolean hasVolume() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The volume. */ public com.google.cloud.netapp.v1.Volume getVolume() { if (volumeBuilder_ == null) { return volume_ == null ? com.google.cloud.netapp.v1.Volume.getDefaultInstance() : volume_; } else { return volumeBuilder_.getMessage(); } } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setVolume(com.google.cloud.netapp.v1.Volume value) { if (volumeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } volume_ = value; } else { volumeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setVolume(com.google.cloud.netapp.v1.Volume.Builder builderForValue) { if (volumeBuilder_ == null) { volume_ = builderForValue.build(); } else { volumeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeVolume(com.google.cloud.netapp.v1.Volume value) { if (volumeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && volume_ != null && volume_ != com.google.cloud.netapp.v1.Volume.getDefaultInstance()) { getVolumeBuilder().mergeFrom(value); } else { volume_ = value; } } else { volumeBuilder_.mergeFrom(value); } if (volume_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearVolume() { bitField0_ = (bitField0_ & ~0x00000004); volume_ = null; if (volumeBuilder_ != null) { volumeBuilder_.dispose(); volumeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.Volume.Builder getVolumeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getVolumeFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.VolumeOrBuilder getVolumeOrBuilder() { if (volumeBuilder_ != null) { return volumeBuilder_.getMessageOrBuilder(); } else { return volume_ == null ? com.google.cloud.netapp.v1.Volume.getDefaultInstance() : volume_; } } /** * * * <pre> * Required. The volume being created. * </pre> * * <code>.google.cloud.netapp.v1.Volume volume = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.Volume, com.google.cloud.netapp.v1.Volume.Builder, com.google.cloud.netapp.v1.VolumeOrBuilder> getVolumeFieldBuilder() { if (volumeBuilder_ == null) { volumeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.Volume, com.google.cloud.netapp.v1.Volume.Builder, com.google.cloud.netapp.v1.VolumeOrBuilder>( getVolume(), getParentForChildren(), isClean()); volume_ = null; } return volumeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.netapp.v1.CreateVolumeRequest) } // @@protoc_insertion_point(class_scope:google.cloud.netapp.v1.CreateVolumeRequest) private static final com.google.cloud.netapp.v1.CreateVolumeRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.netapp.v1.CreateVolumeRequest(); } public static com.google.cloud.netapp.v1.CreateVolumeRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateVolumeRequest> PARSER = new com.google.protobuf.AbstractParser<CreateVolumeRequest>() { @java.lang.Override public CreateVolumeRequest 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<CreateVolumeRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateVolumeRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.netapp.v1.CreateVolumeRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,633
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/AutoscalersStubSettings.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.AutoscalersClient.AggregatedListPagedResponse; import static com.google.cloud.compute.v1.AutoscalersClient.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.AggregatedListAutoscalersRequest; import com.google.cloud.compute.v1.Autoscaler; import com.google.cloud.compute.v1.AutoscalerAggregatedList; import com.google.cloud.compute.v1.AutoscalerList; import com.google.cloud.compute.v1.AutoscalersScopedList; import com.google.cloud.compute.v1.DeleteAutoscalerRequest; import com.google.cloud.compute.v1.GetAutoscalerRequest; import com.google.cloud.compute.v1.InsertAutoscalerRequest; import com.google.cloud.compute.v1.ListAutoscalersRequest; import com.google.cloud.compute.v1.Operation; import com.google.cloud.compute.v1.PatchAutoscalerRequest; import com.google.cloud.compute.v1.UpdateAutoscalerRequest; 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 AutoscalersStub}. * * <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 * AutoscalersStubSettings.Builder autoscalersSettingsBuilder = * AutoscalersStubSettings.newBuilder(); * autoscalersSettingsBuilder * .getSettings() * .setRetrySettings( * autoscalersSettingsBuilder * .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()); * AutoscalersStubSettings autoscalersSettings = autoscalersSettingsBuilder.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 * AutoscalersStubSettings.Builder autoscalersSettingsBuilder = * AutoscalersStubSettings.newBuilder(); * TimedRetryAlgorithm timedRetryAlgorithm = * OperationalTimedPollAlgorithm.create( * RetrySettings.newBuilder() * .setInitialRetryDelayDuration(Duration.ofMillis(500)) * .setRetryDelayMultiplier(1.5) * .setMaxRetryDelayDuration(Duration.ofMillis(5000)) * .setTotalTimeoutDuration(Duration.ofHours(24)) * .build()); * autoscalersSettingsBuilder * .createClusterOperationSettings() * .setPollingAlgorithm(timedRetryAlgorithm) * .build(); * }</pre> */ @Generated("by gapic-generator-java") public class AutoscalersStubSettings extends StubSettings<AutoscalersStubSettings> { /** 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< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse> aggregatedListSettings; private final UnaryCallSettings<DeleteAutoscalerRequest, Operation> deleteSettings; private final OperationCallSettings<DeleteAutoscalerRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings<GetAutoscalerRequest, Autoscaler> getSettings; private final UnaryCallSettings<InsertAutoscalerRequest, Operation> insertSettings; private final OperationCallSettings<InsertAutoscalerRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings<ListAutoscalersRequest, AutoscalerList, ListPagedResponse> listSettings; private final UnaryCallSettings<PatchAutoscalerRequest, Operation> patchSettings; private final OperationCallSettings<PatchAutoscalerRequest, Operation, Operation> patchOperationSettings; private final UnaryCallSettings<UpdateAutoscalerRequest, Operation> updateSettings; private final OperationCallSettings<UpdateAutoscalerRequest, Operation, Operation> updateOperationSettings; private static final PagedListDescriptor< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, Map.Entry<String, AutoscalersScopedList>> AGGREGATED_LIST_PAGE_STR_DESC = new PagedListDescriptor< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, Map.Entry<String, AutoscalersScopedList>>() { @Override public String emptyToken() { return ""; } @Override public AggregatedListAutoscalersRequest injectToken( AggregatedListAutoscalersRequest payload, String token) { return AggregatedListAutoscalersRequest.newBuilder(payload) .setPageToken(token) .build(); } @Override public AggregatedListAutoscalersRequest injectPageSize( AggregatedListAutoscalersRequest payload, int pageSize) { return AggregatedListAutoscalersRequest.newBuilder(payload) .setMaxResults(pageSize) .build(); } @Override public Integer extractPageSize(AggregatedListAutoscalersRequest payload) { return payload.getMaxResults(); } @Override public String extractNextToken(AutoscalerAggregatedList payload) { return payload.getNextPageToken(); } @Override public Iterable<Map.Entry<String, AutoscalersScopedList>> extractResources( AutoscalerAggregatedList payload) { return payload.getItemsMap().entrySet(); } }; private static final PagedListDescriptor<ListAutoscalersRequest, AutoscalerList, Autoscaler> LIST_PAGE_STR_DESC = new PagedListDescriptor<ListAutoscalersRequest, AutoscalerList, Autoscaler>() { @Override public String emptyToken() { return ""; } @Override public ListAutoscalersRequest injectToken( ListAutoscalersRequest payload, String token) { return ListAutoscalersRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListAutoscalersRequest injectPageSize( ListAutoscalersRequest payload, int pageSize) { return ListAutoscalersRequest.newBuilder(payload).setMaxResults(pageSize).build(); } @Override public Integer extractPageSize(ListAutoscalersRequest payload) { return payload.getMaxResults(); } @Override public String extractNextToken(AutoscalerList payload) { return payload.getNextPageToken(); } @Override public Iterable<Autoscaler> extractResources(AutoscalerList payload) { return payload.getItemsList(); } }; private static final PagedListResponseFactory< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse> AGGREGATED_LIST_PAGE_STR_FACT = new PagedListResponseFactory< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse>() { @Override public ApiFuture<AggregatedListPagedResponse> getFuturePagedResponse( UnaryCallable<AggregatedListAutoscalersRequest, AutoscalerAggregatedList> callable, AggregatedListAutoscalersRequest request, ApiCallContext context, ApiFuture<AutoscalerAggregatedList> futureResponse) { PageContext< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, Map.Entry<String, AutoscalersScopedList>> pageContext = PageContext.create(callable, AGGREGATED_LIST_PAGE_STR_DESC, request, context); return AggregatedListPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListAutoscalersRequest, AutoscalerList, ListPagedResponse> LIST_PAGE_STR_FACT = new PagedListResponseFactory< ListAutoscalersRequest, AutoscalerList, ListPagedResponse>() { @Override public ApiFuture<ListPagedResponse> getFuturePagedResponse( UnaryCallable<ListAutoscalersRequest, AutoscalerList> callable, ListAutoscalersRequest request, ApiCallContext context, ApiFuture<AutoscalerList> futureResponse) { PageContext<ListAutoscalersRequest, AutoscalerList, Autoscaler> 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< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse> aggregatedListSettings() { return aggregatedListSettings; } /** Returns the object with the settings used for calls to delete. */ public UnaryCallSettings<DeleteAutoscalerRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the object with the settings used for calls to delete. */ public OperationCallSettings<DeleteAutoscalerRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the object with the settings used for calls to get. */ public UnaryCallSettings<GetAutoscalerRequest, Autoscaler> getSettings() { return getSettings; } /** Returns the object with the settings used for calls to insert. */ public UnaryCallSettings<InsertAutoscalerRequest, Operation> insertSettings() { return insertSettings; } /** Returns the object with the settings used for calls to insert. */ public OperationCallSettings<InsertAutoscalerRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the object with the settings used for calls to list. */ public PagedCallSettings<ListAutoscalersRequest, AutoscalerList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the object with the settings used for calls to patch. */ public UnaryCallSettings<PatchAutoscalerRequest, Operation> patchSettings() { return patchSettings; } /** Returns the object with the settings used for calls to patch. */ public OperationCallSettings<PatchAutoscalerRequest, Operation, Operation> patchOperationSettings() { return patchOperationSettings; } /** Returns the object with the settings used for calls to update. */ public UnaryCallSettings<UpdateAutoscalerRequest, Operation> updateSettings() { return updateSettings; } /** Returns the object with the settings used for calls to update. */ public OperationCallSettings<UpdateAutoscalerRequest, Operation, Operation> updateOperationSettings() { return updateOperationSettings; } public AutoscalersStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonAutoscalersStub.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(AutoscalersStubSettings.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 AutoscalersStubSettings(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(); updateSettings = settingsBuilder.updateSettings().build(); updateOperationSettings = settingsBuilder.updateOperationSettings().build(); } /** Builder for AutoscalersStubSettings. */ public static class Builder extends StubSettings.Builder<AutoscalersStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final PagedCallSettings.Builder< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse> aggregatedListSettings; private final UnaryCallSettings.Builder<DeleteAutoscalerRequest, Operation> deleteSettings; private final OperationCallSettings.Builder<DeleteAutoscalerRequest, Operation, Operation> deleteOperationSettings; private final UnaryCallSettings.Builder<GetAutoscalerRequest, Autoscaler> getSettings; private final UnaryCallSettings.Builder<InsertAutoscalerRequest, Operation> insertSettings; private final OperationCallSettings.Builder<InsertAutoscalerRequest, Operation, Operation> insertOperationSettings; private final PagedCallSettings.Builder< ListAutoscalersRequest, AutoscalerList, ListPagedResponse> listSettings; private final UnaryCallSettings.Builder<PatchAutoscalerRequest, Operation> patchSettings; private final OperationCallSettings.Builder<PatchAutoscalerRequest, Operation, Operation> patchOperationSettings; private final UnaryCallSettings.Builder<UpdateAutoscalerRequest, Operation> updateSettings; private final OperationCallSettings.Builder<UpdateAutoscalerRequest, Operation, Operation> updateOperationSettings; 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(); updateSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateOperationSettings = OperationCallSettings.newBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( aggregatedListSettings, deleteSettings, getSettings, insertSettings, listSettings, patchSettings, updateSettings); initDefaults(this); } protected Builder(AutoscalersStubSettings 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(); updateSettings = settings.updateSettings.toBuilder(); updateOperationSettings = settings.updateOperationSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( aggregatedListSettings, deleteSettings, getSettings, insertSettings, listSettings, patchSettings, updateSettings); } 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 .updateSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params")); builder .deleteOperationSettings() .setInitialCallSettings( UnaryCallSettings .<DeleteAutoscalerRequest, 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 .<InsertAutoscalerRequest, 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 .<PatchAutoscalerRequest, 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 .updateOperationSettings() .setInitialCallSettings( UnaryCallSettings .<UpdateAutoscalerRequest, 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< AggregatedListAutoscalersRequest, AutoscalerAggregatedList, AggregatedListPagedResponse> aggregatedListSettings() { return aggregatedListSettings; } /** Returns the builder for the settings used for calls to delete. */ public UnaryCallSettings.Builder<DeleteAutoscalerRequest, Operation> deleteSettings() { return deleteSettings; } /** Returns the builder for the settings used for calls to delete. */ public OperationCallSettings.Builder<DeleteAutoscalerRequest, Operation, Operation> deleteOperationSettings() { return deleteOperationSettings; } /** Returns the builder for the settings used for calls to get. */ public UnaryCallSettings.Builder<GetAutoscalerRequest, Autoscaler> getSettings() { return getSettings; } /** Returns the builder for the settings used for calls to insert. */ public UnaryCallSettings.Builder<InsertAutoscalerRequest, Operation> insertSettings() { return insertSettings; } /** Returns the builder for the settings used for calls to insert. */ public OperationCallSettings.Builder<InsertAutoscalerRequest, Operation, Operation> insertOperationSettings() { return insertOperationSettings; } /** Returns the builder for the settings used for calls to list. */ public PagedCallSettings.Builder<ListAutoscalersRequest, AutoscalerList, ListPagedResponse> listSettings() { return listSettings; } /** Returns the builder for the settings used for calls to patch. */ public UnaryCallSettings.Builder<PatchAutoscalerRequest, Operation> patchSettings() { return patchSettings; } /** Returns the builder for the settings used for calls to patch. */ public OperationCallSettings.Builder<PatchAutoscalerRequest, Operation, Operation> patchOperationSettings() { return patchOperationSettings; } /** Returns the builder for the settings used for calls to update. */ public UnaryCallSettings.Builder<UpdateAutoscalerRequest, Operation> updateSettings() { return updateSettings; } /** Returns the builder for the settings used for calls to update. */ public OperationCallSettings.Builder<UpdateAutoscalerRequest, Operation, Operation> updateOperationSettings() { return updateOperationSettings; } @Override public AutoscalersStubSettings build() throws IOException { return new AutoscalersStubSettings(this); } } }
oracle/nosql
35,510
kvmain/src/main/java/com/sleepycat/util/PackedInteger.java
/*- * Copyright (C) 2002, 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 com.sleepycat.util; /** * Static methods for reading and writing packed integers. * * <p>Most applications should use the classes in the {@link * com.sleepycat.bind.tuple} package rather than using this class directly.</p> * * @see <a href="../bind/tuple/package-summary.html#integerFormats">Integer Formats</a> */ public class PackedInteger { /** * The maximum number of bytes needed to store an int value (5). */ public static final int MAX_LENGTH = 5; /** * The maximum number of bytes needed to store a long value (9). */ public static final int MAX_LONG_LENGTH = 9; /** * Reads a packed integer at the given buffer offset and returns it. * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the integer that was read. */ public static int readInt(byte[] buf, int off) { boolean negative; int byteLen; int b1 = buf[off++]; if (b1 < -119) { negative = true; byteLen = -b1 - 119; } else if (b1 > 119) { negative = false; byteLen = b1 - 119; } else { return b1; } int value = buf[off++] & 0xFF; if (byteLen > 1) { value |= (buf[off++] & 0xFF) << 8; if (byteLen > 2) { value |= (buf[off++] & 0xFF) << 16; if (byteLen > 3) { value |= (buf[off++] & 0xFF) << 24; } } } return negative ? (-value - 119) : (value + 119); } /** * Reads a packed long integer at the given buffer offset and returns it. * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the long integer that was read. */ public static long readLong(byte[] buf, int off) { boolean negative; int byteLen; int b1 = buf[off++]; if (b1 < -119) { negative = true; byteLen = -b1 - 119; } else if (b1 > 119) { negative = false; byteLen = b1 - 119; } else { return b1; } long value = buf[off++] & 0xFFL; if (byteLen > 1) { value |= (buf[off++] & 0xFFL) << 8; if (byteLen > 2) { value |= (buf[off++] & 0xFFL) << 16; if (byteLen > 3) { value |= (buf[off++] & 0xFFL) << 24; if (byteLen > 4) { value |= (buf[off++] & 0xFFL) << 32; if (byteLen > 5) { value |= (buf[off++] & 0xFFL) << 40; if (byteLen > 6) { value |= (buf[off++] & 0xFFL) << 48; if (byteLen > 7) { value |= (buf[off++] & 0xFFL) << 56; } } } } } } } return negative ? (-value - 119) : (value + 119); } /** * Returns the number of bytes that would be read by {@link #readInt}. * * <p>Because the length is stored in the first byte, this method may be * called with only the first byte of the packed integer in the given * buffer. This method only accesses one byte at the given offset.</p> * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the number of bytes that would be read. */ public static int getReadIntLength(byte[] buf, int off) { int b1 = buf[off]; if (b1 < -119) { return -b1 - 119 + 1; } else if (b1 > 119) { return b1 - 119 + 1; } else { return 1; } } /** * Returns the number of bytes that would be read by {@link #readLong}. * * <p>Because the length is stored in the first byte, this method may be * called with only the first byte of the packed integer in the given * buffer. This method only accesses one byte at the given offset.</p> * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the number of bytes that would be read. */ public static int getReadLongLength(byte[] buf, int off) { /* The length is stored in the same way for int and long. */ return getReadIntLength(buf, off); } /** * Writes a packed integer starting at the given buffer offset and returns * the next offset to be written. * * @param buf the buffer to write to. * * @param offset the offset in the buffer at which to start writing. * * @param value the integer to be written. * * @return the offset past the bytes written. */ public static int writeInt(byte[] buf, int offset, int value) { int byte1Off = offset; boolean negative; if (value < -119) { negative = true; value = -value - 119; } else if (value > 119) { negative = false; value = value - 119; } else { buf[offset++] = (byte) value; return offset; } offset++; buf[offset++] = (byte) value; if ((value & 0xFFFFFF00) == 0) { buf[byte1Off] = negative ? (byte) -120 : (byte) 120; return offset; } buf[offset++] = (byte) (value >>> 8); if ((value & 0xFFFF0000) == 0) { buf[byte1Off] = negative ? (byte) -121 : (byte) 121; return offset; } buf[offset++] = (byte) (value >>> 16); if ((value & 0xFF000000) == 0) { buf[byte1Off] = negative ? (byte) -122 : (byte) 122; return offset; } buf[offset++] = (byte) (value >>> 24); buf[byte1Off] = negative ? (byte) -123 : (byte) 123; return offset; } /** * Writes a packed long integer starting at the given buffer offset and * returns the next offset to be written. * * @param buf the buffer to write to. * * @param offset the offset in the buffer at which to start writing. * * @param value the long integer to be written. * * @return the offset past the bytes written. */ public static int writeLong(byte[] buf, int offset, long value) { int byte1Off = offset; boolean negative; if (value < -119) { negative = true; value = -value - 119; } else if (value > 119) { negative = false; value = value - 119; } else { buf[offset++] = (byte) value; return offset; } offset++; buf[offset++] = (byte) value; if ((value & 0xFFFFFFFFFFFFFF00L) == 0) { buf[byte1Off] = negative ? (byte) -120 : (byte) 120; return offset; } buf[offset++] = (byte) (value >>> 8); if ((value & 0xFFFFFFFFFFFF0000L) == 0) { buf[byte1Off] = negative ? (byte) -121 : (byte) 121; return offset; } buf[offset++] = (byte) (value >>> 16); if ((value & 0xFFFFFFFFFF000000L) == 0) { buf[byte1Off] = negative ? (byte) -122 : (byte) 122; return offset; } buf[offset++] = (byte) (value >>> 24); if ((value & 0xFFFFFFFF00000000L) == 0) { buf[byte1Off] = negative ? (byte) -123 : (byte) 123; return offset; } buf[offset++] = (byte) (value >>> 32); if ((value & 0xFFFFFF0000000000L) == 0) { buf[byte1Off] = negative ? (byte) -124 : (byte) 124; return offset; } buf[offset++] = (byte) (value >>> 40); if ((value & 0xFFFF000000000000L) == 0) { buf[byte1Off] = negative ? (byte) -125 : (byte) 125; return offset; } buf[offset++] = (byte) (value >>> 48); if ((value & 0xFF00000000000000L) == 0) { buf[byte1Off] = negative ? (byte) -126 : (byte) 126; return offset; } buf[offset++] = (byte) (value >>> 56); buf[byte1Off] = negative ? (byte) -127 : (byte) 127; return offset; } /** * Returns the number of bytes that would be written by {@link #writeInt}. * * @param value the integer to be written. * * @return the number of bytes that would be used to write the given * integer. */ public static int getWriteIntLength(int value) { if (value < -119) { value = -value - 119; } else if (value > 119) { value = value - 119; } else { return 1; } if ((value & 0xFFFFFF00) == 0) { return 2; } if ((value & 0xFFFF0000) == 0) { return 3; } if ((value & 0xFF000000) == 0) { return 4; } return 5; } /** * Returns the number of bytes that would be written by {@link #writeLong}. * * @param value the long integer to be written. * * @return the number of bytes that would be used to write the given long * integer. */ public static int getWriteLongLength(long value) { if (value < -119) { value = -value - 119; } else if (value > 119) { value = value - 119; } else { return 1; } if ((value & 0xFFFFFFFFFFFFFF00L) == 0) { return 2; } if ((value & 0xFFFFFFFFFFFF0000L) == 0) { return 3; } if ((value & 0xFFFFFFFFFF000000L) == 0) { return 4; } if ((value & 0xFFFFFFFF00000000L) == 0) { return 5; } if ((value & 0xFFFFFF0000000000L) == 0) { return 6; } if ((value & 0xFFFF000000000000L) == 0) { return 7; } if ((value & 0xFF00000000000000L) == 0) { return 8; } return 9; } /** * Reads a sorted packed integer at the given buffer offset and returns it. * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the integer that was read. */ public static int readSortedInt(byte[] buf, int off) { int byteLen; boolean negative; /* The first byte of the buf stores the length of the value part. */ int b1 = buf[off++] & 0xff; /* Adjust the byteLen to the real length of the value part. */ if (b1 < 0x08) { byteLen = 0x08 - b1; negative = true; } else if (b1 > 0xf7) { byteLen = b1 - 0xf7; negative = false; } else { return b1 - 127; } /* * The following bytes on the buf store the value as a big endian * integer. We extract the significant bytes from the buf and put them * into the value in big endian order. */ int value; if (negative) { value = 0xFFFFFFFF; } else { value = 0; } if (byteLen > 3) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 2) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 1) { value = (value << 8) | (buf[off++] & 0xFF); } value = (value << 8) | (buf[off++] & 0xFF); /* * After get the adjusted value, we have to adjust it back to the * original value. */ if (negative) { value -= 119; } else { value += 121; } return value; } /** * Reads a sorted packed long integer at the given buffer offset and * returns it. * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the long integer that was read. */ public static long readSortedLong(byte[] buf, int off) { int byteLen; boolean negative; /* The first byte of the buf stores the length of the value part. */ int b1 = buf[off++] & 0xff; /* Adjust the byteLen to the real length of the value part. */ if (b1 < 0x08) { byteLen = 0x08 - b1; negative = true; } else if (b1 > 0xf7) { byteLen = b1 - 0xf7; negative = false; } else { return b1 - 127; } /* * The following bytes on the buf store the value as a big endian * integer. We extract the significant bytes from the buf and put them * into the value in big endian order. */ long value; if (negative) { value = 0xFFFFFFFFFFFFFFFFL; } else { value = 0; } if (byteLen > 7) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 6) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 5) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 4) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 3) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 2) { value = (value << 8) | (buf[off++] & 0xFF); } if (byteLen > 1) { value = (value << 8) | (buf[off++] & 0xFF); } value = (value << 8) | (buf[off++] & 0xFF); /* * After obtaining the adjusted value, we have to adjust it back to the * original value. */ if (negative) { value -= 119; } else { value += 121; } return value; } /** * Returns the number of bytes that would be read by {@link * #readSortedInt}. * * <p>Because the length is stored in the first byte, this method may be * called with only the first byte of the packed integer in the given * buffer. This method only accesses one byte at the given offset.</p> * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the number of bytes that would be read. */ public static int getReadSortedIntLength(byte[] buf, int off) { /* The first byte of the buf stores the length of the value part. */ int b1 = buf[off] & 0xff; if (b1 < 0x08) { return 1 + 0x08 - b1; } if (b1 > 0xf7) { return 1 + b1 - 0xf7; } return 1; } /** * Returns the number of bytes that would be read by {@link * #readSortedLong}. * * <p>Because the length is stored in the first byte, this method may be * called with only the first byte of the packed integer in the given * buffer. This method only accesses one byte at the given offset.</p> * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading. * * @return the number of bytes that would be read. */ public static int getReadSortedLongLength(byte[] buf, int off) { /* The length is stored in the same way for int and long. */ return getReadSortedIntLength(buf, off); } /** * Writes a packed sorted integer starting at the given buffer offset and * returns the next offset to be written. * * @param buf the buffer to write to. * * @param offset the offset in the buffer at which to start writing. * * @param value the integer to be written. * * @return the offset past the bytes written. */ public static int writeSortedInt(byte[] buf, int offset, int value) { /* * Values in the inclusive range [-119,120] are stored in a single * byte. For values outside that range, the first byte stores the * number of additional bytes. The additional bytes store * (value + 119 for negative and value - 121 for positive) as an * unsigned big endian integer. */ int byte1Off = offset; offset++; if (value < -119) { /* * If the value < -119, then first adjust the value by adding 119. * Then the adjusted value is stored as an unsigned big endian * integer. */ value += 119; /* * Store the adjusted value as an unsigned big endian integer. * For an negative integer, from left to right, the first * significant byte is the byte which is not equal to 0xFF. Also * please note that, because the adjusted value is stored in big * endian integer, we extract the significant byte from left to * right. * * In the left to right order, if the first byte of the adjusted * value is a significant byte, it will be stored in the 2nd byte * of the buf. Then we will look at the 2nd byte of the adjusted * value to see if this byte is the significant byte, if yes, this * byte will be stored in the 3rd byte of the buf, and the like. */ if ((value | 0x00FFFFFF) != 0xFFFFFFFF) { buf[offset++] = (byte) (value >> 24); } if ((value | 0x0000FFFF) != 0xFFFFFFFF) { buf[offset++] = (byte) (value >> 16); } if ((value | 0x000000FF) != 0xFFFFFFFF) { buf[offset++] = (byte) (value >> 8); } buf[offset++] = (byte) value; /* * valueLen is the length of the value part stored in buf. Because * the first byte of buf is used to stored the length, we need * to subtract one. */ int valueLen = offset - byte1Off - 1; /* * The first byte stores the number of additional bytes. Here we * store the result of 0x08 - valueLen, rather than directly store * valueLen. The reason is to implement natural sort order for * byte-by-byte comparison. */ buf[byte1Off] = (byte) (0x08 - valueLen); } else if (value > 120) { /* * If the value > 120, then first adjust the value by subtracting * 121. Then the adjusted value is stored as an unsigned big endian * integer. */ value -= 121; /* * Store the adjusted value as an unsigned big endian integer. * For a positive integer, from left to right, the first * significant byte is the byte which is not equal to 0x00. * * In the left to right order, if the first byte of the adjusted * value is a significant byte, it will be stored in the 2nd byte * of the buf. Then we will look at the 2nd byte of the adjusted * value to see if this byte is the significant byte, if yes, this * byte will be stored in the 3rd byte of the buf, and the like. */ if ((value & 0xFF000000) != 0) { buf[offset++] = (byte) (value >> 24); } if ((value & 0xFFFF0000) != 0) { buf[offset++] = (byte) (value >> 16); } if ((value & 0xFFFFFF00) != 0) { buf[offset++] = (byte) (value >> 8); } buf[offset++] = (byte) value; /* * valueLen is the length of the value part stored in buf. Because * the first byte of buf is used to stored the length, we need to * subtract one. */ int valueLen = offset - byte1Off - 1; /* * The first byte stores the number of additional bytes. Here we * store the result of 0xF7 + valueLen, rather than directly store * valueLen. The reason is to implement natural sort order for * byte-by-byte comparison. */ buf[byte1Off] = (byte) (0xF7 + valueLen); } else { /* * If -119 <= value <= 120, only one byte is needed to store the * value. The stored value is the original value plus 127. */ buf[byte1Off] = (byte) (value + 127); } return offset; } /** * Writes a packed sorted long integer starting at the given buffer offset * and returns the next offset to be written. * * @param buf the buffer to write to. * * @param offset the offset in the buffer at which to start writing. * * @param value the long integer to be written. * * @return the offset past the bytes written. */ public static int writeSortedLong(byte[] buf, int offset, long value) { /* * Values in the inclusive range [-119,120] are stored in a single * byte. For values outside that range, the first byte stores the * number of additional bytes. The additional bytes store * (value + 119 for negative and value - 121 for positive) as an * unsigned big endian integer. */ int byte1Off = offset; offset++; if (value < -119) { /* * If the value < -119, then first adjust the value by adding 119. * Then the adjusted value is stored as an unsigned big endian * integer. */ value += 119; /* * Store the adjusted value as an unsigned big endian integer. * For an negative integer, from left to right, the first * significant byte is the byte which is not equal to 0xFF. Also * please note that, because the adjusted value is stored in big * endian integer, we extract the significant byte from left to * right. * * In the left to right order, if the first byte of the adjusted * value is a significant byte, it will be stored in the 2nd byte * of the buf. Then we will look at the 2nd byte of the adjusted * value to see if this byte is the significant byte, if yes, this * byte will be stored in the 3rd byte of the buf, and the like. */ if ((value | 0x00FFFFFFFFFFFFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 56); } if ((value | 0x0000FFFFFFFFFFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 48); } if ((value | 0x000000FFFFFFFFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 40); } if ((value | 0x00000000FFFFFFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 32); } if ((value | 0x0000000000FFFFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 24); } if ((value | 0x000000000000FFFFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 16); } if ((value | 0x00000000000000FFL) != 0xFFFFFFFFFFFFFFFFL) { buf[offset++] = (byte) (value >> 8); } buf[offset++] = (byte) value; /* * valueLen is the length of the value part stored in buf. Because * the first byte of buf is used to stored the length, so we need * to minus one. */ int valueLen = offset - byte1Off - 1; /* * The first byte stores the number of additional bytes. Here we * store the result of 0x08 - valueLen, rather than directly store * valueLen. The reason is to implement nature sort order for * byte-by-byte comparison. */ buf[byte1Off] = (byte) (0x08 - valueLen); } else if (value > 120) { /* * If the value > 120, then first adjust the value by subtracting * 119. Then the adjusted value is stored as an unsigned big endian * integer. */ value -= 121; /* * Store the adjusted value as an unsigned big endian integer. * For a positive integer, from left to right, the first * significant byte is the byte which is not equal to 0x00. * * In the left to right order, if the first byte of the adjusted * value is a significant byte, it will be stored in the 2nd byte * of the buf. Then we will look at the 2nd byte of the adjusted * value to see if this byte is the significant byte, if yes, this * byte will be stored in the 3rd byte of the buf, and the like. */ if ((value & 0xFF00000000000000L) != 0L) { buf[offset++] = (byte) (value >> 56); } if ((value & 0xFFFF000000000000L) != 0L) { buf[offset++] = (byte) (value >> 48); } if ((value & 0xFFFFFF0000000000L) != 0L) { buf[offset++] = (byte) (value >> 40); } if ((value & 0xFFFFFFFF00000000L) != 0L) { buf[offset++] = (byte) (value >> 32); } if ((value & 0xFFFFFFFFFF000000L) != 0L) { buf[offset++] = (byte) (value >> 24); } if ((value & 0xFFFFFFFFFFFF0000L) != 0L) { buf[offset++] = (byte) (value >> 16); } if ((value & 0xFFFFFFFFFFFFFF00L) != 0L) { buf[offset++] = (byte) (value >> 8); } buf[offset++] = (byte) value; /* * valueLen is the length of the value part stored in buf. Because * the first byte of buf is used to stored the length, so we need * to minus one. */ int valueLen = offset - byte1Off - 1; /* * The first byte stores the number of additional bytes. Here we * store the result of 0xF7 + valueLen, rather than directly store * valueLen. The reason is to implement nature sort order for * byte-by-byte comparison. */ buf[byte1Off] = (byte) (0xF7 + valueLen); } else { /* * If -119 <= value <= 120, only one byte is needed to store the * value. The stored value is the original value adds 127. */ buf[byte1Off] = (byte) (value + 127); } return offset; } /** * Returns the number of bytes that would be written by {@link * #writeSortedInt}. * * @param value the integer to be written. * * @return the number of bytes that would be used to write the given * integer. */ public static int getWriteSortedIntLength(int value) { if (value < -119) { /* Adjust the value. */ value += 119; /* * Find the left most significant byte of the adjusted value, and * return the length accordingly. */ if ((value | 0x000000FF) == 0xFFFFFFFF) { return 2; } if ((value | 0x0000FFFF) == 0xFFFFFFFF) { return 3; } if ((value | 0x00FFFFFF) == 0xFFFFFFFF) { return 4; } } else if (value > 120) { /* Adjust the value. */ value -= 121; /* * Find the left most significant byte of the adjusted value, and * return the length accordingly. */ if ((value & 0xFFFFFF00) == 0) { return 2; } if ((value & 0xFFFF0000) == 0) { return 3; } if ((value & 0xFF000000) == 0) { return 4; } } else { /* * If -119 <= value <= 120, only one byte is needed to store the * value. */ return 1; } return 5; } /** * Returns the number of bytes that would be written by {@link * #writeSortedLong}. * * @param value the long integer to be written. * * @return the number of bytes that would be used to write the given long * integer. */ public static int getWriteSortedLongLength(long value) { if (value < -119) { /* Adjust the value. */ value += 119; /* * Find the left most significant byte of the adjusted value, and * return the length accordingly. */ if ((value | 0x00000000000000FFL) == 0xFFFFFFFFFFFFFFFFL) { return 2; } if ((value | 0x000000000000FFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 3; } if ((value | 0x0000000000FFFFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 4; } if ((value | 0x00000000FFFFFFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 5; } if ((value | 0x000000FFFFFFFFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 6; } if ((value | 0x0000FFFFFFFFFFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 7; } if ((value | 0x00FFFFFFFFFFFFFFL) == 0xFFFFFFFFFFFFFFFFL) { return 8; } } else if (value > 120) { /* Adjust the value. */ value -= 121; /* * Find the left most significant byte of the adjusted value, and * return the length accordingly. */ if ((value & 0xFFFFFFFFFFFFFF00L) == 0L) { return 2; } if ((value & 0xFFFFFFFFFFFF0000L) == 0L) { return 3; } if ((value & 0xFFFFFFFFFF000000L) == 0L) { return 4; } if ((value & 0xFFFFFFFF00000000L) == 0L) { return 5; } if ((value & 0xFFFFFF0000000000L) == 0L) { return 6; } if ((value & 0xFFFF000000000000L) == 0L) { return 7; } if ((value & 0xFF00000000000000L) == 0L) { return 8; } } else { /* * If -119 <= value <= 120, only one byte is needed to store the * value. */ return 1; } return 9; } /* <!-- begin JE only --> */ /** * @hidden * Reads a reverse-packed integer ending at the given buffer offset and * returns it. * * To get the length of a reverse-packed integer before reading, call * {@link #getReadIntLength} passing the offset to the last byte. * * @param buf the buffer to read from. * * @param off the offset in the buffer at which to start reading, which is * the index of the last byte of the integer in the buffer. * * @return the integer that was read. */ public static int readReverseInt(byte[] buf, int off) { boolean negative; int byteLen; int b1 = buf[off]; if (b1 < -119) { negative = true; byteLen = -b1 - 119; } else if (b1 > 119) { negative = false; byteLen = b1 - 119; } else { return b1; } int value = buf[--off] & 0xFF; if (byteLen > 1) { value |= (buf[--off] & 0xFF) << 8; if (byteLen > 2) { value |= (buf[--off] & 0xFF) << 16; if (byteLen > 3) { value |= (buf[--off] & 0xFF) << 24; } } } return negative ? (-value - 119) : (value + 119); } /** * @hidden * Writes a reverse-packed integer starting at the given buffer offset and * returns the next offset to be written. * * To get the length of a reverse-packed integer before writing, call * {@link #getWriteIntLength}. * * @param buf the buffer to write to. * * @param off the offset in the buffer at which to start writing, which * will be the index of the first byte of the integer in the buffer. * * @param value the integer to be written. * * @return the offset past the bytes written. */ public static int writeReverseInt(byte[] buf, int off, int value) { final boolean negative; final int nextOff = off + getWriteIntLength(value); if (value < -119) { negative = true; value = -value - 119; } else if (value > 119) { negative = false; value = value - 119; } else { buf[off] = (byte) value; return off + 1; } final int byte1Off = nextOff - 1; off = byte1Off; buf[--off] = (byte) value; if ((value & 0xFFFFFF00) == 0) { buf[byte1Off] = negative ? (byte) -120 : (byte) 120; return nextOff; } buf[--off] = (byte) (value >>> 8); if ((value & 0xFFFF0000) == 0) { buf[byte1Off] = negative ? (byte) -121 : (byte) 121; return nextOff; } buf[--off] = (byte) (value >>> 16); if ((value & 0xFF000000) == 0) { buf[byte1Off] = negative ? (byte) -122 : (byte) 122; return nextOff; } buf[--off] = (byte) (value >>> 24); buf[byte1Off] = negative ? (byte) -123 : (byte) 123; return nextOff; } /* <!-- end JE only --> */ }
google/closure-templates
33,684
java/tests/com/google/template/soy/conformance/SoyConformanceTest.java
/* * Copyright 2017 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.template.soy.conformance; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.io.CharSource; import com.google.protobuf.TextFormat; import com.google.protobuf.TextFormat.ParseException; import com.google.template.soy.base.SourceFilePath; import com.google.template.soy.base.internal.SoyFileSupplier; import com.google.template.soy.base.internal.StableSoyFileSupplier; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyError; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.testing.SoyFileSetParserBuilder; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test case for {@link SoyConformance}. */ @RunWith(JUnit4.class) public class SoyConformanceTest { @Test public void testBannedFunction() { assertViolation( "requirement: {\n" + " banned_function {\n" + " function: 'checkNotNull'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{checkNotNull(['xxx', 'bar', 'yyy', 'baz'])}\n" + "{/template}"); } @Test public void testTemplateWithSameNameAsBannedFunction() { assertNoViolation( "requirement: {\n" + " banned_function: {\n" + " function: 'checkNotNull'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template checkNotNull}\n" + "This should be allowed.\n" + "{/template}"); } @Test public void testBannedExtern() { assertViolation( "requirement: {\n" + " banned_function {\n" + " function: \"{ext} from 'path/to/externs.soy'\"\n" + " }\n" + " error_message: 'foo'" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "import {ext} from 'path/to/externs.soy';\n" + "{template foo}\n" + " {ext()}\n" + "{/template}"), SourceFilePath.forTest("foo/bar/baz.soy")), new StableSoyFileSupplier( CharSource.wrap( "{namespace ns.externs}\n" + "{export extern ext: () => ?}\n" + " {jsimpl namespace=\"ns.functions\" function=\"fn2\" /}\n" + "{/extern}"), SourceFilePath.forTest("path/to/externs.soy"))); } @Test public void testBannedPrintDirective() { assertViolation( "requirement: {\n" + " banned_directive: {\n" + " directive: '|escapeUri'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{print 'blah' |escapeUri}\n" + "{/template}"); } @Test public void testTemplateWithSameNameAsBannedPrintDirective() { assertNoViolation( "requirement: {\n" + " banned_directive: {\n" + " directive: '|filterUri'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template filterUri}\n" + "This should be allowed.\n" + "{/template}"); } @Test public void testBannedCommandText() { assertViolation( "requirement: {\n" + " banned_css_selector: {\n" + " selector: 'goog-inline-block'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{css('goog-inline-block')}\n" + "{/template}\n"); } @Test public void testBannedCommandTextInNonTargetedCommand() { assertNoViolation( "requirement: {\n" + " banned_css_selector: {\n" + " selector: 'goog-inline-block'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{print 'goog-inline-block'}\n" + "{/template}\n"); } @Test public void testBannedClassSelectorMdcPrefix() { assertViolation( "requirement: {\n" + " banned_css_selector: {\n" + " selector: 'mdc-'\n" + " when_prefix: true\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{css('mdc-button')}\n" + "{/template}\n"); } @Test public void testBannedClassSelectorMdcSubstring() { assertNoViolation( "requirement: {\n" + " banned_css_selector: {\n" + " selector: 'mdc-'\n" + " when_prefix: true\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "{css('other-prefix-mdc-button')}\n" + "{/template}\n"); } @Test public void testExemptedFileDoesNotCauseErrors() { assertNoViolation( "requirement: {\n" + " banned_function {\n" + " function: 'checkNotNull'\n" + " }\n" + " error_message: 'foo'" + " exempt: 'foo/bar/baz.soy'\n" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "{template foo}\n" + "{checkNotNull(['xxx', 'bar', 'yyy', 'baz'])}\n" + "{/template}"), SourceFilePath.forTest("foo/bar/baz.soy"))); } @Test public void testExemptedEntriesAreSubstrings() { assertNoViolation( "requirement: {\n" + " banned_function {\n" + " function: 'checkNotNull'\n" + " }\n" + " error_message: 'foo'" + " exempt: 'c/foo/bar/baz.soy'\n" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "{template foo}\n" + "{checkNotNull(['xxx', 'bar', 'yyy', 'baz'])}\n" + "{/template}"), SourceFilePath.forTest("a/b/c/foo/bar/baz.soy"))); } @Test public void testExemptedSubstringsAreContiguous() { assertViolation( "requirement: {\n" + " banned_function {\n" + " function: 'checkNotNull'\n" + " }\n" + " error_message: 'foooo'" + " exempt: 'foo/c/bar/baz.soy'\n" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "{template foo}\n" + "{checkNotNull(['xxx', 'bar', 'yyy', 'baz'])}\n" + "{/template}"), SourceFilePath.forTest("a/b/c/foo/bar/baz.soy"))); } @Test public void testBannedRawText() { assertViolation( "requirement: {\n" + " banned_raw_text: {\n" + " text: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + "foo\n" + "{/template}"); } @Test public void testBannedRawTextDoesNotIncludeTemplateNames() { assertNoViolation( "requirement: {\n" + " banned_raw_text: {\n" + " text: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "bar\n" + "{/template}"); } @Test public void testBannedRawTextDoesNotIncludeComments() { assertNoViolation( "requirement: {\n" + " banned_raw_text: {\n" + " text: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<!-- foo -->\n" + "{/template}"); } @Test public void testBannedRawTextIgnoresHtmlAttributes() { assertNoViolation( "requirement: {\n" + " banned_raw_text: {\n" + " text: 'foo'\n" + " except_in_html_attribute: 'link'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<a link=\"foo\"></a>\n" + "{/template}"); } @Test public void bannedHtmlTag() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagDifferentCase() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" // Tag name is case insensitive: Div will be converted to div + " tag: 'Div'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" // Tag name is case insensitive. + " <DIV>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagMultipleTags() { // Banned both iframe and script, using iframe. assertViolation( "requirement: {\n" + " banned_html_tag: {\n" // Tag name is case-insensitive + " tag: 'IFRAME'\n" + " tag: 'script'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + "<iframe src='#'>test</iframe>\n" + "{/template}"); } @Test public void bannedHtmlTagNoViolation() { // Banned script, using iframe. assertNoViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'script'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + "<iframe src='foo.js'>test</iframe>\n" + "{/template}"); // Banned both iframe and script, using other tags. assertNoViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'iframe'\n" + " tag: 'script'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + "<div><p></p></div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithAttribute() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div contenteditable>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithAttributeDifferentCase() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div CONTENTEDITABLE>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithNonStaticAttribute() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + "{@param baz: bool}" + " <div {if $baz}contenteditable{/if}>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithMultipleAttributes() { assertViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " when_attribute_possibly_present: 'style'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div contenteditable style='color:red;'>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithAttributeNoViolation() { assertNoViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithMultipleAttributesNoViolation() { assertNoViolation( "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'div'\n" + " when_attribute_possibly_present: 'contenteditable'\n" + " when_attribute_possibly_present: 'style'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template bar}\n" + " <div contenteditable>test</div>\n" + "{/template}"); } @Test public void bannedHtmlTagWithBannedAndRequiredAttribute() { String requirement = "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'script'\n" + " when_attribute_possibly_missing: 'src'\n" + " when_attribute_possibly_present: 'defer'\n" + " }\n" + " error_message: 'foo'" + "}"; assertNoViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script src=\"foo.js\"></script>\n" + "{/template}"); assertViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script defer></script>\n" + "{/template}"); assertViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script src=\"foo.js\" defer></script>\n" + "{/template}"); assertViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script></script>\n" + "{/template}"); } @Test public void bannedHtmlTagWithRequiredAttribute() { String requirement = "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'script'\n" + " when_attribute_possibly_missing: 'src'\n" + " }\n" + " error_message: 'foo'" + "}"; // Fail if a script is set without a src assertViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script>console.log('js is run here');</script>\n" + "{/template}"); // As long as the src attribute is set there are no violations assertNoViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script src=\"foo.js\">console.log('js is ignored here');</script>\n" + "{/template}"); assertNoViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script src=\"\">console.log('js is ignored here');</script>\n" + "{/template}"); assertNoViolation( requirement, "{namespace ns}\n" + "{template bar}\n" + " <script src>console.log('js is ignored here');</script>\n" + "{/template}"); } @Test public void bannedHtmlTagWithExemptedAttributes() { String check = "requirement: {\n" + " banned_html_tag: {\n" + " tag: 'script'\n" + " exempt_attribute: {\n" + " name: 'type'\n" + " value: 'application/ld+json'\n" + " }\n" + " exempt_attribute: {\n" + " name: 'keyA'\n" + " }\n" + " }\n" + " error_message: 'foo'" + "}"; assertNoViolation( check, "{namespace ns}\n" + "{template bar}\n" + " <script type=\"application/ld+json\"></script>\n" + " <script keyA></script>\n" + " <script keyA src=\"foo.js\"></script>\n" + " <script keyA=\"\"></script>\n" + " <script keyA=\"anything\"></script>\n" + "{/template}"); assertViolation( check, "{namespace ns}\n" + "{template bar}\n" + " <script></script>\n" + "{/template}"); assertViolation( check, "{namespace ns}\n" + "{template bar}\n" + " <script src =\"foo.js\"></script>\n" + "{/template}"); assertViolation( check, "{namespace ns}\n" + "{template bar}\n" + " <script type=\"module\"></script>\n" + "{/template}"); } @Test public void testBanInlineEventHandlers() { assertViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<div onclick='bar'></div>\n" + "{/template}"); assertViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<div ONCLICK='bar'></div>\n" + "{/template}"); assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<div on='bar'></div>\n" + "{/template}"); } @Test public void testRequireStrictHtml() { String config = "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.RequireStrictHtml'\n" + " }\n" + " error_message: 'foo'" + "}"; assertNoViolation(config, "{namespace ns}\n" + "{template foo}\n" + "{/template}"); assertViolation( config, "{namespace ns}\n" + "{template foo stricthtml=\"false\"}\n" + "{/template}"); assertNoViolation( config, "{namespace ns}\n" + "{template foo kind=\"text\"}\n" + "{/template}"); } // regression test, this used to not be detected since we only issued errors if the attribute was // defined inside a kind="attributes" block @Test public void testBanInlineEventHandlers_attributes() { assertViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo kind=\"attributes\"}\n" + "ONCLICK='bar'\n" + "{/template}"); } // regression test for a situation involving script tags, the old version wouldn't catch this but // i don't know why...i suspect a subtle bug in the way SlicedRawTextNodes are created @Test public void testBanInlineEventHandlers_script() { assertViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + " {@param jsUrl : ?}{@param callback : ?}\n" + "<script id=\"base-js\" src=\"{$jsUrl}\" async onload=\"{$callback}\"></script>\n" + "{/template}"); } @Test public void testBanInlineEventHandlersExemptions() { assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + " exempt: 'foo/bar/baz.soy'" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "{template foo}\n" + "<script onload='foo();'></script>\n" + "{/template}"), SourceFilePath.forTest("foo/bar/baz.soy"))); } // Regression test for a bug where we used to essentially ignore exemptions if there were // multiple files in a compilation unit @Test public void testBanInlineEventHandlersIsTooAggressiveWithExemptions() { assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + " exempt: 'foo/bar/baz.soy'" + "}", new StableSoyFileSupplier( CharSource.wrap( "{namespace ns}\n" + "{template foo}\n" + "<script onload='foo();'></script>\n" + "{/template}"), SourceFilePath.forTest("foo/bar/baz.soy")), new StableSoyFileSupplier( CharSource.wrap("{namespace ns2}\n" + "{template noViolation}{/template}"), SourceFilePath.forTest("foo/bar/quux.soy"))); } @Test public void testBanInlineEventHandlers_NotJs() { assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanInlineEventHandlers'\n" + " }\n" + " error_message: 'foo'" + " " + "}", "{namespace ns}\n" + "{template foo}\n" + "<div foo='bar'></div>\n" + "{/template}"); } @Test public void testBanFragmentNavigation() { assertViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanFragmentNavigation'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<a href='#foo'></a>" + "{/template}"); assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanFragmentNavigation'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<a href='./#foo'></a>" + "{/template}"); assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanFragmentNavigation'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<a href='#'></a>" + "{/template}"); assertNoViolation( "requirement: {\n" + " custom: {\n" + " java_class: 'com.google.template.soy.conformance.BanFragmentNavigation'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}\n" + "{template foo}\n" + "<some-custom-tag href='#'></some-custom-tag>" + "{/template}"); } @Test public void testBannedCssSelector() { assertViolation( "requirement: {\n" + " banned_css_selector {\n" + " selector: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}{template bar}{css('foo')}{/template}"); assertViolation( "requirement: {\n" + " banned_css_selector {\n" + " selector: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}{template bar}{css('foo')}{/template}"); assertViolation( "requirement: {\n" + " banned_css_selector {\n" + " selector: 'foo'\n" + " }\n" + " error_message: 'foo'" + "}", "{namespace ns}{template bar}{@param foo : ?}{css($foo, 'foo')}{/template}"); } @Test public void testBanXidForCssObfuscation_valid() { assertNoViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "\n" + "{template foo}\n" + " {@param foo: string}\n" + " {let $baz: css('baz') /}\n" + " <div class=\"{css('foo')} {$baz}\n" + " {if $foo == xid('bar')}{css('bar')}{/if}\n" + " {$foo == xid('baz') ? css('a') : css('b')}\n" + " {call shouldIgnoreThis}{param foo: xid('foo') /}{/call}\"\n" + " data-foo=\"{xid('foo')}\">\n" + " {call bar}\n" + " {param fooClasses: css('foo') /}\n" + " {param barClasses kind=\"text\"}\n" + " {css('bar')}\n" + " {/param}\n" + " {param complexClass kind=\"text\"}\n" + " {call shouldIgnoreThis}{param foo: xid('foo') /}{/call}\n" + " {/param}\n" + " {param foo: xid('foo') /}\n" + " {param bar kind=\"text\"}{xid('bar')}{/param}\n" + " {/call}\n" + " </div>\n" + "{/template}\n" + "\n" + "{template bar}\n" + " {@param fooClasses: string}\n" + " {@param barClasses: string}\n" + " {@param complexClass: string}\n" + " {@param foo: string}\n" + " {@param bar: string}\n" + " {$fooClasses + $barClasses + $complexClass + $foo + $bar}\n" + "{/template}\n" + "\n" + "{template shouldIgnoreThis}\n" + " {@param foo: string}\n" + " {if $foo == xid('foo')}{css('bar')}{/if}\n" + "{/template}\n"); } @Test public void testBanXidForCssObfuscation_inClassAttribute() { assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " <div class=\"{css('foo')} {xid('bar')}\"></div>\n" + "{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {let $bar kind=\"text\"}{xid('bar')}{/let}\n" + " <div class=\"{css('foo')} {$bar}\"></div>\n" + "{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {let $baz: xid('baz') /}\n" + " {let $bar kind=\"text\"}{$baz}{/let}\n" + " <div class=\"{css('foo')} {$bar}\"></div>\n" + "{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {@param foo: bool}\n" + " <div class=\"{css('foo')} {$foo ? css('bar') : xid('baz')}\"></div>\n" + "{/template}"); } @Test public void testBanXidForCssObfuscation_inPotentialClassParam() { assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {call bar}\n" + " {param classes kind=\"text\"}{css('foo')} {xid('bar')}{/param}\n" + " {/call}\n" + "{/template}\n" + "{template bar}{@param classes: string}<div class=\"{$classes}\"></div>{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {call bar}\n" + " {param class: xid('foo') /}\n" + " {/call}\n" + "{/template}\n" + "{template bar}{@param class: string}<div class=\"{$class}\"></div>{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {let $bar: xid('bar') /}\n" + " {call bar}\n" + " {param myClass: $bar /}\n" + " {/call}\n" + "{/template}\n" + "{template bar}{@param myClass: string}<div class=\"{$myClass}\"></div>{/template}"); assertViolation( "requirement { ban_xid_for_css_obfuscation {} error_message: 'foo' }", "{namespace ns}\n" + "{template foo}\n" + " {let $baz: xid('baz') /}\n" + " {let $bar kind=\"text\"}{$baz}{/let}\n" + " {call bar}\n" + " {param myClasses kind=\"text\"}{$bar}{/param}\n" + " {/call}\n" + "{/template}\n" + "{template bar}\n" + " {@param myClasses: string}\n" + " <div class=\"{$myClasses}\"></div>\n" + "{/template}"); } private SoyError assertViolation(String textProto, String input) { ImmutableList<SoyError> violations = getViolations(textProto, input); assertThat(violations).hasSize(1); return Iterables.getOnlyElement(violations); } private SoyError assertViolation(String textProto, SoyFileSupplier... soyFileSuppliers) { ImmutableList<SoyError> violations = getViolations(textProto, soyFileSuppliers); assertThat(violations).hasSize(1); return Iterables.getOnlyElement(violations); } private void assertViolations(String textProto, String input, int size) { ImmutableList<SoyError> violations = getViolations(textProto, input); assertThat(violations).hasSize(size); } private void assertNoViolation(String textProto, String input) { ImmutableList<SoyError> violations = getViolations(textProto, input); assertThat(violations).isEmpty(); } private void assertNoViolation(String textProto, SoyFileSupplier... soyFileSuppliers) { ImmutableList<SoyError> violations = getViolations(textProto, soyFileSuppliers); assertThat(violations).isEmpty(); } private ImmutableList<SoyError> getViolations(String textProto, String input) { return getViolations(textProto, SoyFileSetParserBuilder.forFileContents(input)); } private ImmutableList<SoyError> getViolations(String textProto, SoyFileSupplier... suppliers) { return getViolations(textProto, SoyFileSetParserBuilder.forSuppliers(suppliers)); } private ImmutableList<SoyError> getViolations(String textProto, SoyFileSetParserBuilder builder) { ValidatedConformanceConfig config = parseConfigProto(textProto); ErrorReporter errorReporter = ErrorReporter.create(); builder.setConformanceConfig(config).errorReporter(errorReporter).parse(); ImmutableList<SoyError> errors = errorReporter.getErrors(); Set<SoyErrorKind> expectedErrorKinds = new HashSet<>(); for (RuleWithExemptions rule : config.getRules()) { expectedErrorKinds.add(rule.getRule().error); } for (SoyError actualError : errors) { if (!expectedErrorKinds.contains(actualError.errorKind())) { throw new AssertionError( "Found non-conformance error!: " + actualError + "\nexpected kind to be one of: " + expectedErrorKinds + " actual is: " + actualError.errorKind()); } } return errors; } private ValidatedConformanceConfig parseConfigProto(String textProto) { ConformanceConfig.Builder builder = ConformanceConfig.newBuilder(); try { TextFormat.merge(textProto, builder); } catch (ParseException pe) { throw new RuntimeException(pe); } return ValidatedConformanceConfig.create(builder.build()); } }
googleapis/google-cloud-java
35,368
java-dataproc/proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ParameterValidation.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/workflow_templates.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataproc.v1; /** * * * <pre> * Configuration for parameter validation. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.ParameterValidation} */ public final class ParameterValidation extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.ParameterValidation) ParameterValidationOrBuilder { private static final long serialVersionUID = 0L; // Use ParameterValidation.newBuilder() to construct. private ParameterValidation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ParameterValidation() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ParameterValidation(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.WorkflowTemplatesProto .internal_static_google_cloud_dataproc_v1_ParameterValidation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.WorkflowTemplatesProto .internal_static_google_cloud_dataproc_v1_ParameterValidation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.ParameterValidation.class, com.google.cloud.dataproc.v1.ParameterValidation.Builder.class); } private int validationTypeCase_ = 0; @SuppressWarnings("serial") private java.lang.Object validationType_; public enum ValidationTypeCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { REGEX(1), VALUES(2), VALIDATIONTYPE_NOT_SET(0); private final int value; private ValidationTypeCase(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 ValidationTypeCase valueOf(int value) { return forNumber(value); } public static ValidationTypeCase forNumber(int value) { switch (value) { case 1: return REGEX; case 2: return VALUES; case 0: return VALIDATIONTYPE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ValidationTypeCase getValidationTypeCase() { return ValidationTypeCase.forNumber(validationTypeCase_); } public static final int REGEX_FIELD_NUMBER = 1; /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> * * @return Whether the regex field is set. */ @java.lang.Override public boolean hasRegex() { return validationTypeCase_ == 1; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> * * @return The regex. */ @java.lang.Override public com.google.cloud.dataproc.v1.RegexValidation getRegex() { if (validationTypeCase_ == 1) { return (com.google.cloud.dataproc.v1.RegexValidation) validationType_; } return com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ @java.lang.Override public com.google.cloud.dataproc.v1.RegexValidationOrBuilder getRegexOrBuilder() { if (validationTypeCase_ == 1) { return (com.google.cloud.dataproc.v1.RegexValidation) validationType_; } return com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } public static final int VALUES_FIELD_NUMBER = 2; /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> * * @return Whether the values field is set. */ @java.lang.Override public boolean hasValues() { return validationTypeCase_ == 2; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> * * @return The values. */ @java.lang.Override public com.google.cloud.dataproc.v1.ValueValidation getValues() { if (validationTypeCase_ == 2) { return (com.google.cloud.dataproc.v1.ValueValidation) validationType_; } return com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance(); } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ @java.lang.Override public com.google.cloud.dataproc.v1.ValueValidationOrBuilder getValuesOrBuilder() { if (validationTypeCase_ == 2) { return (com.google.cloud.dataproc.v1.ValueValidation) validationType_; } return com.google.cloud.dataproc.v1.ValueValidation.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 (validationTypeCase_ == 1) { output.writeMessage(1, (com.google.cloud.dataproc.v1.RegexValidation) validationType_); } if (validationTypeCase_ == 2) { output.writeMessage(2, (com.google.cloud.dataproc.v1.ValueValidation) validationType_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (validationTypeCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.cloud.dataproc.v1.RegexValidation) validationType_); } if (validationTypeCase_ == 2) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 2, (com.google.cloud.dataproc.v1.ValueValidation) validationType_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataproc.v1.ParameterValidation)) { return super.equals(obj); } com.google.cloud.dataproc.v1.ParameterValidation other = (com.google.cloud.dataproc.v1.ParameterValidation) obj; if (!getValidationTypeCase().equals(other.getValidationTypeCase())) return false; switch (validationTypeCase_) { case 1: if (!getRegex().equals(other.getRegex())) return false; break; case 2: if (!getValues().equals(other.getValues())) 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 (validationTypeCase_) { case 1: hash = (37 * hash) + REGEX_FIELD_NUMBER; hash = (53 * hash) + getRegex().hashCode(); break; case 2: hash = (37 * hash) + VALUES_FIELD_NUMBER; hash = (53 * hash) + getValues().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.ParameterValidation parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ParameterValidation parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ParameterValidation parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataproc.v1.ParameterValidation prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Configuration for parameter validation. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.ParameterValidation} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.ParameterValidation) com.google.cloud.dataproc.v1.ParameterValidationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.WorkflowTemplatesProto .internal_static_google_cloud_dataproc_v1_ParameterValidation_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.WorkflowTemplatesProto .internal_static_google_cloud_dataproc_v1_ParameterValidation_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.ParameterValidation.class, com.google.cloud.dataproc.v1.ParameterValidation.Builder.class); } // Construct using com.google.cloud.dataproc.v1.ParameterValidation.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (regexBuilder_ != null) { regexBuilder_.clear(); } if (valuesBuilder_ != null) { valuesBuilder_.clear(); } validationTypeCase_ = 0; validationType_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataproc.v1.WorkflowTemplatesProto .internal_static_google_cloud_dataproc_v1_ParameterValidation_descriptor; } @java.lang.Override public com.google.cloud.dataproc.v1.ParameterValidation getDefaultInstanceForType() { return com.google.cloud.dataproc.v1.ParameterValidation.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataproc.v1.ParameterValidation build() { com.google.cloud.dataproc.v1.ParameterValidation result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataproc.v1.ParameterValidation buildPartial() { com.google.cloud.dataproc.v1.ParameterValidation result = new com.google.cloud.dataproc.v1.ParameterValidation(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.dataproc.v1.ParameterValidation result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs(com.google.cloud.dataproc.v1.ParameterValidation result) { result.validationTypeCase_ = validationTypeCase_; result.validationType_ = this.validationType_; if (validationTypeCase_ == 1 && regexBuilder_ != null) { result.validationType_ = regexBuilder_.build(); } if (validationTypeCase_ == 2 && valuesBuilder_ != null) { result.validationType_ = valuesBuilder_.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.dataproc.v1.ParameterValidation) { return mergeFrom((com.google.cloud.dataproc.v1.ParameterValidation) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataproc.v1.ParameterValidation other) { if (other == com.google.cloud.dataproc.v1.ParameterValidation.getDefaultInstance()) return this; switch (other.getValidationTypeCase()) { case REGEX: { mergeRegex(other.getRegex()); break; } case VALUES: { mergeValues(other.getValues()); break; } case VALIDATIONTYPE_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(getRegexFieldBuilder().getBuilder(), extensionRegistry); validationTypeCase_ = 1; break; } // case 10 case 18: { input.readMessage(getValuesFieldBuilder().getBuilder(), extensionRegistry); validationTypeCase_ = 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 validationTypeCase_ = 0; private java.lang.Object validationType_; public ValidationTypeCase getValidationTypeCase() { return ValidationTypeCase.forNumber(validationTypeCase_); } public Builder clearValidationType() { validationTypeCase_ = 0; validationType_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.RegexValidation, com.google.cloud.dataproc.v1.RegexValidation.Builder, com.google.cloud.dataproc.v1.RegexValidationOrBuilder> regexBuilder_; /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> * * @return Whether the regex field is set. */ @java.lang.Override public boolean hasRegex() { return validationTypeCase_ == 1; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> * * @return The regex. */ @java.lang.Override public com.google.cloud.dataproc.v1.RegexValidation getRegex() { if (regexBuilder_ == null) { if (validationTypeCase_ == 1) { return (com.google.cloud.dataproc.v1.RegexValidation) validationType_; } return com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } else { if (validationTypeCase_ == 1) { return regexBuilder_.getMessage(); } return com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ public Builder setRegex(com.google.cloud.dataproc.v1.RegexValidation value) { if (regexBuilder_ == null) { if (value == null) { throw new NullPointerException(); } validationType_ = value; onChanged(); } else { regexBuilder_.setMessage(value); } validationTypeCase_ = 1; return this; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ public Builder setRegex(com.google.cloud.dataproc.v1.RegexValidation.Builder builderForValue) { if (regexBuilder_ == null) { validationType_ = builderForValue.build(); onChanged(); } else { regexBuilder_.setMessage(builderForValue.build()); } validationTypeCase_ = 1; return this; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ public Builder mergeRegex(com.google.cloud.dataproc.v1.RegexValidation value) { if (regexBuilder_ == null) { if (validationTypeCase_ == 1 && validationType_ != com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance()) { validationType_ = com.google.cloud.dataproc.v1.RegexValidation.newBuilder( (com.google.cloud.dataproc.v1.RegexValidation) validationType_) .mergeFrom(value) .buildPartial(); } else { validationType_ = value; } onChanged(); } else { if (validationTypeCase_ == 1) { regexBuilder_.mergeFrom(value); } else { regexBuilder_.setMessage(value); } } validationTypeCase_ = 1; return this; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ public Builder clearRegex() { if (regexBuilder_ == null) { if (validationTypeCase_ == 1) { validationTypeCase_ = 0; validationType_ = null; onChanged(); } } else { if (validationTypeCase_ == 1) { validationTypeCase_ = 0; validationType_ = null; } regexBuilder_.clear(); } return this; } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ public com.google.cloud.dataproc.v1.RegexValidation.Builder getRegexBuilder() { return getRegexFieldBuilder().getBuilder(); } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ @java.lang.Override public com.google.cloud.dataproc.v1.RegexValidationOrBuilder getRegexOrBuilder() { if ((validationTypeCase_ == 1) && (regexBuilder_ != null)) { return regexBuilder_.getMessageOrBuilder(); } else { if (validationTypeCase_ == 1) { return (com.google.cloud.dataproc.v1.RegexValidation) validationType_; } return com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } } /** * * * <pre> * Validation based on regular expressions. * </pre> * * <code>.google.cloud.dataproc.v1.RegexValidation regex = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.RegexValidation, com.google.cloud.dataproc.v1.RegexValidation.Builder, com.google.cloud.dataproc.v1.RegexValidationOrBuilder> getRegexFieldBuilder() { if (regexBuilder_ == null) { if (!(validationTypeCase_ == 1)) { validationType_ = com.google.cloud.dataproc.v1.RegexValidation.getDefaultInstance(); } regexBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.RegexValidation, com.google.cloud.dataproc.v1.RegexValidation.Builder, com.google.cloud.dataproc.v1.RegexValidationOrBuilder>( (com.google.cloud.dataproc.v1.RegexValidation) validationType_, getParentForChildren(), isClean()); validationType_ = null; } validationTypeCase_ = 1; onChanged(); return regexBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.ValueValidation, com.google.cloud.dataproc.v1.ValueValidation.Builder, com.google.cloud.dataproc.v1.ValueValidationOrBuilder> valuesBuilder_; /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> * * @return Whether the values field is set. */ @java.lang.Override public boolean hasValues() { return validationTypeCase_ == 2; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> * * @return The values. */ @java.lang.Override public com.google.cloud.dataproc.v1.ValueValidation getValues() { if (valuesBuilder_ == null) { if (validationTypeCase_ == 2) { return (com.google.cloud.dataproc.v1.ValueValidation) validationType_; } return com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance(); } else { if (validationTypeCase_ == 2) { return valuesBuilder_.getMessage(); } return com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance(); } } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ public Builder setValues(com.google.cloud.dataproc.v1.ValueValidation value) { if (valuesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } validationType_ = value; onChanged(); } else { valuesBuilder_.setMessage(value); } validationTypeCase_ = 2; return this; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ public Builder setValues(com.google.cloud.dataproc.v1.ValueValidation.Builder builderForValue) { if (valuesBuilder_ == null) { validationType_ = builderForValue.build(); onChanged(); } else { valuesBuilder_.setMessage(builderForValue.build()); } validationTypeCase_ = 2; return this; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ public Builder mergeValues(com.google.cloud.dataproc.v1.ValueValidation value) { if (valuesBuilder_ == null) { if (validationTypeCase_ == 2 && validationType_ != com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance()) { validationType_ = com.google.cloud.dataproc.v1.ValueValidation.newBuilder( (com.google.cloud.dataproc.v1.ValueValidation) validationType_) .mergeFrom(value) .buildPartial(); } else { validationType_ = value; } onChanged(); } else { if (validationTypeCase_ == 2) { valuesBuilder_.mergeFrom(value); } else { valuesBuilder_.setMessage(value); } } validationTypeCase_ = 2; return this; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ public Builder clearValues() { if (valuesBuilder_ == null) { if (validationTypeCase_ == 2) { validationTypeCase_ = 0; validationType_ = null; onChanged(); } } else { if (validationTypeCase_ == 2) { validationTypeCase_ = 0; validationType_ = null; } valuesBuilder_.clear(); } return this; } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ public com.google.cloud.dataproc.v1.ValueValidation.Builder getValuesBuilder() { return getValuesFieldBuilder().getBuilder(); } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ @java.lang.Override public com.google.cloud.dataproc.v1.ValueValidationOrBuilder getValuesOrBuilder() { if ((validationTypeCase_ == 2) && (valuesBuilder_ != null)) { return valuesBuilder_.getMessageOrBuilder(); } else { if (validationTypeCase_ == 2) { return (com.google.cloud.dataproc.v1.ValueValidation) validationType_; } return com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance(); } } /** * * * <pre> * Validation based on a list of allowed values. * </pre> * * <code>.google.cloud.dataproc.v1.ValueValidation values = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.ValueValidation, com.google.cloud.dataproc.v1.ValueValidation.Builder, com.google.cloud.dataproc.v1.ValueValidationOrBuilder> getValuesFieldBuilder() { if (valuesBuilder_ == null) { if (!(validationTypeCase_ == 2)) { validationType_ = com.google.cloud.dataproc.v1.ValueValidation.getDefaultInstance(); } valuesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataproc.v1.ValueValidation, com.google.cloud.dataproc.v1.ValueValidation.Builder, com.google.cloud.dataproc.v1.ValueValidationOrBuilder>( (com.google.cloud.dataproc.v1.ValueValidation) validationType_, getParentForChildren(), isClean()); validationType_ = null; } validationTypeCase_ = 2; onChanged(); return valuesBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.ParameterValidation) } // @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.ParameterValidation) private static final com.google.cloud.dataproc.v1.ParameterValidation DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.ParameterValidation(); } public static com.google.cloud.dataproc.v1.ParameterValidation getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ParameterValidation> PARSER = new com.google.protobuf.AbstractParser<ParameterValidation>() { @java.lang.Override public ParameterValidation 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<ParameterValidation> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ParameterValidation> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataproc.v1.ParameterValidation getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
35,570
truffle/src/com.oracle.truffle.polyglot/src/com/oracle/truffle/polyglot/JDKSupport.java
/* * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.polyglot; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.lang.reflect.Method; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; import com.oracle.truffle.api.InternalResource; import com.oracle.truffle.api.InternalResource.OS; import com.oracle.truffle.api.InternalResource.CPUArchitecture; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.impl.Accessor; import com.oracle.truffle.api.impl.Accessor.JavaLangSupport; import com.oracle.truffle.api.impl.Accessor.ModulesAccessor; import com.oracle.truffle.api.impl.asm.ClassWriter; import com.oracle.truffle.api.impl.asm.FieldVisitor; import com.oracle.truffle.api.impl.asm.MethodVisitor; import com.oracle.truffle.api.impl.asm.Opcodes; import jdk.internal.access.JavaLangAccess; import jdk.internal.access.SharedSecrets; import jdk.internal.module.Modules; final class JDKSupport { /* * We use reflective access to addEnableAccess and addEnableNativeAccessToAllUnnamed to make * Truffle compilable on JDK-17. */ private static final Method ADD_ENABLE_NATIVE_ACCESS; private static final Method ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED; static { if (Runtime.version().feature() >= 21) { try { Class<?> langAccessClass = Class.forName("jdk.internal.access.JavaLangAccess"); ADD_ENABLE_NATIVE_ACCESS = langAccessClass.getDeclaredMethod("addEnableNativeAccess", Module.class); ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED = langAccessClass.getDeclaredMethod("addEnableNativeAccessToAllUnnamed"); } catch (ReflectiveOperationException re) { throw new InternalError(re); } } else { // On JDK-17 do nothing ADD_ENABLE_NATIVE_ACCESS = null; ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED = null; } } private static final ModulesAccessor MODULES_ACCESSOR = initializeModuleAccessor(); @SuppressWarnings("restricted") private static ModulesAccessor initializeModuleAccessor() { String attachLibPath = System.getProperty("truffle.attach.library"); if (attachLibPath == null) { if (isUnsupportedPlatform()) { performTruffleAttachLoadFailureAction("Truffle is running on an unsupported platform where the TruffleAttach library is unavailable.", null); return null; } try { Path truffleAttachRoot = InternalResourceCache.installRuntimeResource(new LibTruffleAttachResource(), LibTruffleAttachResource.ID); Path libAttach = truffleAttachRoot.resolve("bin").resolve(System.mapLibraryName("truffleattach")); attachLibPath = libAttach.toString(); } catch (IOException ioe) { performTruffleAttachLoadFailureAction("The Truffle API JAR is missing the 'truffleattach' resource, likely due to issues when Truffle was repackaged into a fat JAR.", ioe); return null; } } try { try { System.load(attachLibPath); } catch (UnsatisfiedLinkError failedToLoad) { performTruffleAttachLoadFailureAction("Unable to load the TruffleAttach library.", failedToLoad); return null; } catch (IllegalCallerException illegalCaller) { String vmOption = "--enable-native-access=" + (JDKSupport.class.getModule().isNamed() ? "org.graalvm.truffle" : "ALL-UNNAMED"); performTruffleAttachLoadFailureAction(String.format("Failed to load the TruffleAttach library. The Truffle module does not have native access enabled. " + "To resolve this, pass the following VM option: %s.", vmOption), illegalCaller); return null; } ModulesAccessor accessor; if (ModulesAccessor.class.getModule().isNamed()) { accessor = new DirectImpl(Accessor.ModulesAccessor.class); } else { accessor = new IsolatedImpl(Accessor.ModulesAccessor.class); } Module javaBase = ModuleLayer.boot().findModule("java.base").orElseThrow(); addExports0(javaBase, "jdk.internal.module", accessor.getTargetModule()); addExports0(javaBase, "jdk.internal.access", accessor.getTargetModule()); return accessor; } catch (ReflectiveOperationException re) { throw new InternalError(re); } } private static boolean isUnsupportedPlatform() { try { return OS.getCurrent() == OS.UNSUPPORTED || CPUArchitecture.getCurrent() == CPUArchitecture.UNSUPPORTED; } catch (IllegalStateException ise) { /* * We suppress this error in the JDKSupport static initializer to prevent it from being * obscured by a long and unreadable chain of exception causes. If this error occurs * here, it will be handled later during engine creation. */ return true; } } private static native void addExports0(Module m1, String pn, Module m2); private static void performTruffleAttachLoadFailureAction(String reason, Throwable t) { String action = System.getProperty("polyglotimpl.AttachLibraryFailureAction", "warn"); switch (action) { case "ignore" -> { } case "warn" -> { PolyglotEngineImpl.logFallback(formatErrorMessage(reason)); } case "diagnose" -> { StringWriter message = new StringWriter(); try (PrintWriter err = new PrintWriter(message)) { err.println(formatErrorMessage(reason)); t.printStackTrace(err); } PolyglotEngineImpl.logFallback(message.toString()); } case "throw" -> throw new InternalError(formatErrorMessage(reason), t); default -> throw new IllegalArgumentException("Invalid polyglotimpl.AttachLibraryFailureAction system property value. Supported values are ignore, warn, diagnose, throw"); } } private static String formatErrorMessage(String reason) { return String.format( """ [engine] WARNING: %s As a result, the optimized Truffle runtime is unavailable, and Truffle cannot provide native access to languages and tools. To customize the behavior of this warning, use the 'polyglotimpl.AttachLibraryFailureAction' system property. Allowed values are: - ignore: Do not print this warning. - warn: Print this warning (default value). - diagnose: Print this warning along with the exception cause. - throw: Throw an exception instead of printing this warning. """, reason); } private JDKSupport() { } static void exportTransitivelyTo(Module clientModule) { if (isExportedTo(clientModule)) { return; } Module truffleModule = Truffle.class.getModule(); forEach(clientModule, EnumSet.of(Edge.READS, Edge.USES), (m) -> m != truffleModule && m.canRead(truffleModule), JDKSupport::exportFromTo); } static void enableNativeAccess(Module clientModule) { forEach(clientModule, EnumSet.of(Edge.READS), (m) -> true, (m) -> { ModulesAccessor accessor = getModulesAccessor(); /* * The accessor is null if libtruffleattach cannot be loaded, such as when Truffle with * a fallback runtime is loaded by multiple class loaders. In this case, we do not * delegate enable-native-access and let the JDK emit native access warnings. */ if (accessor != null) { if (m.isNamed()) { getModulesAccessor().addEnableNativeAccess(m); } else { getModulesAccessor().addEnableNativeAccessToAllUnnamed(); } } }); } @SuppressWarnings("restricted") static ModulesAccessor getModulesAccessor() { return MODULES_ACCESSOR; } private static void forEach(Module rootModule, Set<Edge> edges, Predicate<? super Module> filter, Consumer<? super Module> action) { ModuleLayer layer = rootModule.getLayer(); Set<Module> targetModules = new HashSet<>(); Deque<Module> todo = new ArrayDeque<>(); /* * The module graph with reads and provides edges is not a DAG. We need to keeping track of * visited modules to detect cycles. */ Set<Module> visited = new HashSet<>(); todo.add(rootModule); Map<String, Set<Module>> serviceDictionary = null; while (!todo.isEmpty()) { Module module = todo.removeFirst(); if (visited.add(module) && Objects.equals(module.getLayer(), layer) && filter.test(module)) { targetModules.add(module); ModuleDescriptor descriptor = module.getDescriptor(); if (descriptor == null) { /* * Unnamed module: Deprecated. The unnamed module does not have a module * descriptor, but reads the entire module graph. For unnamed modules we do not * do transitive export because we would have to open the Truffle module to all * modules in the module layer. */ } else if (descriptor.isAutomatic()) { /* * Automatic module: An unnamed module has an artificial module descriptor, with * only the mandated `requires java.base` directive. But an automatic module * reads the entire module graph. For automatic modules we do not do transitive * export because we would have to open the Truffle module to all modules in the * module layer. */ } else { /* * Named module with a module descriptor: Export transitively to all modules * required by the named module. */ if (edges.contains(Edge.READS)) { for (ModuleDescriptor.Requires requires : descriptor.requires()) { Module requiredModule = findModule(layer, requires); if (requiredModule != null) { todo.add(requiredModule); } } } if (edges.contains(Edge.USES)) { // Open also to modules providing a service consumed by the module. Set<String> usedServices = descriptor.uses(); if (!usedServices.isEmpty()) { if (serviceDictionary == null) { serviceDictionary = new HashMap<>(); for (Module m : layer.modules()) { if (filter.test(m)) { for (ModuleDescriptor.Provides provides : m.getDescriptor().provides()) { serviceDictionary.computeIfAbsent(provides.service(), (k) -> new HashSet<>()).add(m); } } } } for (String service : usedServices) { todo.addAll(serviceDictionary.getOrDefault(service, Set.of())); } } } } } } targetModules.forEach(action); } private static Module findModule(ModuleLayer layer, ModuleDescriptor.Requires requires) { Optional<Module> moduleOrNull = layer.findModule(requires.name()); if (moduleOrNull.isPresent()) { return moduleOrNull.get(); } else if (requires.modifiers().contains(ModuleDescriptor.Requires.Modifier.STATIC)) { // Optional runtime dependency may not be available. return null; } else { throw new AssertionError(String.format("A non-optional module %s not found in the module layer %s.", requires.name(), layer)); } } private static boolean isExportedTo(Module clientModule) { Module truffleModule = Truffle.class.getModule(); for (String pack : truffleModule.getPackages()) { if (!truffleModule.isExported(pack, clientModule)) { return false; } } return true; } private static void exportFromTo(Module clientModule) { Module truffleModule = Truffle.class.getModule(); if (truffleModule != clientModule) { Set<String> packages = truffleModule.getPackages(); for (String pkg : packages) { boolean exported = truffleModule.isExported(pkg, clientModule); if (!exported) { truffleModule.addExports(pkg, clientModule); } } } } private enum Edge { READS, USES } /* * When using a named module we do not need to do anything and we can just call the Modules * class. We used a qualified export to export it to this class. */ private static final class DirectImpl extends Accessor.ModulesAccessor { private final Class<?> baseClass; DirectImpl(Class<?> baseClass) { if (!baseClass.getModule().isNamed()) { throw new IllegalStateException(""); } this.baseClass = baseClass; } @Override public void addExports(Module base, String p, Module target) { Modules.addExports(base, p, target); } @Override public void addExportsToAllUnnamed(Module base, String p) { Modules.addExportsToAllUnnamed(base, p); } @Override public void addOpens(Module base, String p, Module target) { Modules.addOpens(base, p, target); } @Override public void addOpensToAllUnnamed(Module base, String p) { Modules.addOpensToAllUnnamed(base, p); } @Override public void addEnableNativeAccess(Module module) { if (ADD_ENABLE_NATIVE_ACCESS != null) { try { ADD_ENABLE_NATIVE_ACCESS.invoke(SharedSecrets.getJavaLangAccess(), module); } catch (ReflectiveOperationException re) { throw new InternalError(re); } } } @Override public void addEnableNativeAccessToAllUnnamed() { if (ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED != null) { try { ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED.invoke(SharedSecrets.getJavaLangAccess()); } catch (ReflectiveOperationException re) { throw new InternalError(re); } } } @Override public Module getTargetModule() { return baseClass.getModule(); } @Override public JavaLangSupport getJavaLangSupport() { return JavaLangSupportImpl.INSTANCE; } private static final class JavaLangSupportImpl extends JavaLangSupport { private static final JavaLangAccess JAVA_LANG_ACCESS = SharedSecrets.getJavaLangAccess(); static final JavaLangSupport INSTANCE = new JavaLangSupportImpl(); private JavaLangSupportImpl() { } @Override public Thread currentCarrierThread() { return JAVA_LANG_ACCESS.currentCarrierThread(); } } } /* * When using a named module we do not need to do anything and we can just call the Modules * class. We used a qualified export to export it to this class. */ private static final class IsolatedImpl extends Accessor.ModulesAccessor { private final MethodHandle addExports; private final MethodHandle addExportsToAllUnnamed; private final MethodHandle addOpens; private final MethodHandle addOpensToAllUnnamed; private final MethodHandle addEnableNativeAccess; private final MethodHandle addEnableNativeAccessToAllUnnamed; private final MethodHandle currentCarrierThread; private final Module targetModule; IsolatedImpl(Class<?> baseClass) throws ReflectiveOperationException { final String moduleName = "org.graalvm.truffle.generated"; final String targetPackage = baseClass.getPackageName() + ".generated"; final String className = targetPackage + ".GeneratedModules"; final String binaryClassName = className.replace('.', '/'); ClassWriter cw = new ClassWriter(0); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, binaryClassName, null, "java/lang/Object", null); FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "javaLangAccess", "Ljdk/internal/access/JavaLangAccess;", null, null); fv.visitEnd(); MethodVisitor clinit = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null); clinit.visitCode(); clinit.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/access/SharedSecrets", "getJavaLangAccess", "()Ljdk/internal/access/JavaLangAccess;", false); clinit.visitFieldInsn(Opcodes.PUTSTATIC, binaryClassName, "javaLangAccess", "Ljdk/internal/access/JavaLangAccess;"); clinit.visitInsn(Opcodes.RETURN); clinit.visitMaxs(1, 0); clinit.visitEnd(); MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); constructor.visitCode(); constructor.visitVarInsn(Opcodes.ALOAD, 0); constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); constructor.visitInsn(Opcodes.RETURN); constructor.visitMaxs(1, 1); constructor.visitEnd(); MethodVisitor mv1 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addExports", "(Ljava/lang/Module;Ljava/lang/String;Ljava/lang/Module;)V", null, null); mv1.visitCode(); mv1.visitVarInsn(Opcodes.ALOAD, 0); // Load first argument (Module base) mv1.visitVarInsn(Opcodes.ALOAD, 1); // Load second argument (String p) mv1.visitVarInsn(Opcodes.ALOAD, 2); // Load third argument (Module target) mv1.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/module/Modules", "addExports", "(Ljava/lang/Module;Ljava/lang/String;Ljava/lang/Module;)V", false); mv1.visitInsn(Opcodes.RETURN); mv1.visitMaxs(3, 3); mv1.visitEnd(); MethodVisitor mv2 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addExportsToAllUnnamed", "(Ljava/lang/Module;Ljava/lang/String;)V", null, null); mv2.visitCode(); mv2.visitVarInsn(Opcodes.ALOAD, 0); // Load first argument (Module target) mv2.visitVarInsn(Opcodes.ALOAD, 1); // Load second argument (String p) mv2.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/module/Modules", "addExportsToAllUnnamed", "(Ljava/lang/Module;Ljava/lang/String;)V", false); mv2.visitInsn(Opcodes.RETURN); mv2.visitMaxs(2, 2); mv2.visitEnd(); MethodVisitor mv3 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addOpens", "(Ljava/lang/Module;Ljava/lang/String;Ljava/lang/Module;)V", null, null); mv3.visitCode(); mv3.visitVarInsn(Opcodes.ALOAD, 0); // Load first argument (Module base) mv3.visitVarInsn(Opcodes.ALOAD, 1); // Load second argument (String p) mv3.visitVarInsn(Opcodes.ALOAD, 2); // Load third argument (Module target) mv3.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/module/Modules", "addOpens", "(Ljava/lang/Module;Ljava/lang/String;Ljava/lang/Module;)V", false); mv3.visitInsn(Opcodes.RETURN); mv3.visitMaxs(3, 3); mv3.visitEnd(); MethodVisitor mv4 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addOpensToAllUnnamed", "(Ljava/lang/Module;Ljava/lang/String;)V", null, null); mv4.visitCode(); mv4.visitVarInsn(Opcodes.ALOAD, 0); // Load first argument (Module target) mv4.visitVarInsn(Opcodes.ALOAD, 1); // Load second argument (String p) mv4.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/module/Modules", "addOpensToAllUnnamed", "(Ljava/lang/Module;Ljava/lang/String;)V", false); mv4.visitInsn(Opcodes.RETURN); mv4.visitMaxs(2, 2); mv4.visitEnd(); MethodVisitor mv5 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addEnableNativeAccess", "(Ljava/lang/Module;)V", null, null); mv5.visitCode(); if (ADD_ENABLE_NATIVE_ACCESS != null) { mv5.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/access/SharedSecrets", "getJavaLangAccess", "()Ljdk/internal/access/JavaLangAccess;", false); mv5.visitVarInsn(Opcodes.ALOAD, 0); // Load first argument (Module module) mv5.visitMethodInsn(Opcodes.INVOKEINTERFACE, "jdk/internal/access/JavaLangAccess", "addEnableNativeAccess", "(Ljava/lang/Module;)Ljava/lang/Module;", true); } mv5.visitInsn(Opcodes.RETURN); mv5.visitMaxs(2, 2); mv5.visitEnd(); MethodVisitor mv6 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "addEnableNativeAccessToAllUnnamed", "()V", null, null); mv6.visitCode(); if (ADD_ENABLE_NATIVE_ACCESS_TO_ALL_UNNAMED != null) { mv6.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/internal/access/SharedSecrets", "getJavaLangAccess", "()Ljdk/internal/access/JavaLangAccess;", false); mv6.visitMethodInsn(Opcodes.INVOKEINTERFACE, "jdk/internal/access/JavaLangAccess", "addEnableNativeAccessToAllUnnamed", "()V", true); } mv6.visitInsn(Opcodes.RETURN); mv6.visitMaxs(1, 1); mv6.visitEnd(); MethodVisitor mv7 = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "currentCarrierThread", "()Ljava/lang/Thread;", null, null); mv7.visitCode(); mv7.visitFieldInsn(Opcodes.GETSTATIC, binaryClassName, "javaLangAccess", "Ljdk/internal/access/JavaLangAccess;"); mv7.visitMethodInsn(Opcodes.INVOKEINTERFACE, "jdk/internal/access/JavaLangAccess", "currentCarrierThread", "()Ljava/lang/Thread;", true); mv7.visitInsn(Opcodes.ARETURN); mv7.visitMaxs(1, 0); mv7.visitEnd(); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); // Create a ModuleDescriptor for the new module ModuleDescriptor descriptor = ModuleDescriptor.newModule(moduleName).exports(targetPackage).build(); // Create a ModuleFinder that finds the module and class ModuleFinder finder = new ModuleFinder() { public Optional<ModuleReference> find(String name) { if (name.equals(moduleName)) { return Optional.of(new ModuleReference(descriptor, null) { @Override @SuppressWarnings("hiding") public ModuleReader open() throws IOException { return new ModuleReader() { @Override public Optional<ByteBuffer> read(String name) throws IOException { if (name.equals(binaryClassName + ".class")) { return Optional.of(ByteBuffer.wrap(classBytes)); } return Optional.empty(); } @Override public void close() throws IOException { } public Optional<URI> find(String name) throws IOException { return Optional.empty(); } public Stream<String> list() throws IOException { return Stream.empty(); } }; } }); } return Optional.empty(); } @Override public Set<ModuleReference> findAll() { return Collections.singleton(find(moduleName).get()); } }; // Resolve the configuration for the new module layer based on the boot layer ModuleLayer bootLayer = ModuleLayer.boot(); Configuration cf = bootLayer.configuration().resolve(finder, ModuleFinder.of(), Collections.singleton(moduleName)); // Define a new module layer with the correct parent layer and class loader ModuleLayer layer = bootLayer.defineModulesWithOneLoader(cf, ClassLoader.getSystemClassLoader()); // Load the class from the module layer Class<?> generatedClass = layer.findLoader(moduleName).loadClass(className); this.targetModule = generatedClass.getModule(); MethodHandles.Lookup l = MethodHandles.lookup(); l.accessClass(generatedClass); this.addExports = l.findStatic(generatedClass, "addExports", MethodType.methodType(void.class, Module.class, String.class, Module.class)); this.addExportsToAllUnnamed = l.findStatic(generatedClass, "addExportsToAllUnnamed", MethodType.methodType(void.class, Module.class, String.class)); this.addOpens = l.findStatic(generatedClass, "addOpens", MethodType.methodType(void.class, Module.class, String.class, Module.class)); this.addOpensToAllUnnamed = l.findStatic(generatedClass, "addOpensToAllUnnamed", MethodType.methodType(void.class, Module.class, String.class)); this.addEnableNativeAccess = l.findStatic(generatedClass, "addEnableNativeAccess", MethodType.methodType(void.class, Module.class)); this.addEnableNativeAccessToAllUnnamed = l.findStatic(generatedClass, "addEnableNativeAccessToAllUnnamed", MethodType.methodType(void.class)); this.currentCarrierThread = l.findStatic(generatedClass, "currentCarrierThread", MethodType.methodType(Thread.class)); } @Override public Module getTargetModule() { return targetModule; } @Override public void addExports(Module base, String p, Module target) { try { addExports.invokeExact(base, p, target); } catch (Throwable e) { throw new InternalError(e); } } @Override public void addExportsToAllUnnamed(Module base, String p) { try { addExportsToAllUnnamed.invokeExact(base, p); } catch (Throwable e) { throw new InternalError(e); } } @Override public void addOpens(Module base, String p, Module target) { try { addOpens.invokeExact(base, p, target); } catch (Throwable e) { throw new InternalError(e); } } @Override public void addOpensToAllUnnamed(Module base, String p) { try { addOpensToAllUnnamed.invokeExact(base, p); } catch (Throwable e) { throw new InternalError(e); } } @Override public void addEnableNativeAccess(Module module) { try { addEnableNativeAccess.invokeExact(module); } catch (Throwable e) { throw new InternalError(e); } } @Override public void addEnableNativeAccessToAllUnnamed() { try { addEnableNativeAccessToAllUnnamed.invokeExact(); } catch (Throwable e) { throw new InternalError(e); } } @Override public JavaLangSupport getJavaLangSupport() { return JavaLangSupportImpl.INSTANCE; } private static final class JavaLangSupportImpl extends JavaLangSupport { /* * For performance reasons, it is necessary for CURRENT_CARRIER_THREAD to be declared as * static final. */ private static final MethodHandle CURRENT_CARRIER_THREAD; static { if (JDKSupport.MODULES_ACCESSOR == null) { throw new IllegalStateException("JavaLangAccessorImpl initialized before JDKSupport."); } else if (!(JDKSupport.MODULES_ACCESSOR instanceof IsolatedImpl)) { throw new IllegalStateException("JDKSupport.MODULES_ACCESSOR initialized with wrong type " + JDKSupport.MODULES_ACCESSOR.getClass()); } else { CURRENT_CARRIER_THREAD = ((IsolatedImpl) JDKSupport.MODULES_ACCESSOR).currentCarrierThread; } } private static final JavaLangSupport INSTANCE = new JavaLangSupportImpl(); private JavaLangSupportImpl() { /* * Ensure the CURRENT_CARRIER_THREAD method handle is initialized by invoking it. * This prevents the interpreter from triggering class initialization during the * virtual thread hooks which must not trigger class loading or suspend the * VirtualThread. */ currentCarrierThread(); } @Override public Thread currentCarrierThread() { try { return (Thread) CURRENT_CARRIER_THREAD.invokeExact(); } catch (Throwable e) { throw new InternalError(e); } } } } @InternalResource.Id(value = LibTruffleAttachResource.ID, componentId = "engine", optional = true) static final class LibTruffleAttachResource implements InternalResource { static final String ID = "libtruffleattach"; LibTruffleAttachResource() { } @Override public void unpackFiles(Env env, Path targetDirectory) throws IOException { if (env.inNativeImageBuild() && !env.inContextPreinitialization()) { // The truffleattach library is not needed in native-image. return; } Path base = basePath(env); env.unpackResourceFiles(base.resolve("files"), targetDirectory, base); } @Override public String versionHash(Env env) throws IOException { Path base = basePath(env); return env.readResourceLines(base.resolve("sha256")).get(0); } private static Path basePath(Env env) { return Path.of("META-INF", "resources", "engine", ID, env.getOS().toString(), env.getCPUArchitecture().toString()); } } }
googleapis/google-cloud-java
35,324
java-maps-fleetengine/proto-google-maps-fleetengine-v1/src/main/java/com/google/maps/fleetengine/v1/SearchTripsResponse.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/maps/fleetengine/v1/trip_api.proto // Protobuf Java Version: 3.25.8 package com.google.maps.fleetengine.v1; /** * * * <pre> * SearchTrips response message. * </pre> * * Protobuf type {@code maps.fleetengine.v1.SearchTripsResponse} */ public final class SearchTripsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:maps.fleetengine.v1.SearchTripsResponse) SearchTripsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SearchTripsResponse.newBuilder() to construct. private SearchTripsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchTripsResponse() { trips_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchTripsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.fleetengine.v1.TripApi .internal_static_maps_fleetengine_v1_SearchTripsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.fleetengine.v1.TripApi .internal_static_maps_fleetengine_v1_SearchTripsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.fleetengine.v1.SearchTripsResponse.class, com.google.maps.fleetengine.v1.SearchTripsResponse.Builder.class); } public static final int TRIPS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.maps.fleetengine.v1.Trip> trips_; /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ @java.lang.Override public java.util.List<com.google.maps.fleetengine.v1.Trip> getTripsList() { return trips_; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.maps.fleetengine.v1.TripOrBuilder> getTripsOrBuilderList() { return trips_; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ @java.lang.Override public int getTripsCount() { return trips_.size(); } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ @java.lang.Override public com.google.maps.fleetengine.v1.Trip getTrips(int index) { return trips_.get(index); } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ @java.lang.Override public com.google.maps.fleetengine.v1.TripOrBuilder getTripsOrBuilder(int index) { return trips_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < trips_.size(); i++) { output.writeMessage(1, trips_.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 < trips_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, trips_.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.maps.fleetengine.v1.SearchTripsResponse)) { return super.equals(obj); } com.google.maps.fleetengine.v1.SearchTripsResponse other = (com.google.maps.fleetengine.v1.SearchTripsResponse) obj; if (!getTripsList().equals(other.getTripsList())) 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 (getTripsCount() > 0) { hash = (37 * hash) + TRIPS_FIELD_NUMBER; hash = (53 * hash) + getTripsList().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.maps.fleetengine.v1.SearchTripsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.fleetengine.v1.SearchTripsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.fleetengine.v1.SearchTripsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.fleetengine.v1.SearchTripsResponse 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.maps.fleetengine.v1.SearchTripsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.fleetengine.v1.SearchTripsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.fleetengine.v1.SearchTripsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.fleetengine.v1.SearchTripsResponse 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.maps.fleetengine.v1.SearchTripsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.maps.fleetengine.v1.SearchTripsResponse 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.maps.fleetengine.v1.SearchTripsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.fleetengine.v1.SearchTripsResponse 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.maps.fleetengine.v1.SearchTripsResponse 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> * SearchTrips response message. * </pre> * * Protobuf type {@code maps.fleetengine.v1.SearchTripsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:maps.fleetengine.v1.SearchTripsResponse) com.google.maps.fleetengine.v1.SearchTripsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.fleetengine.v1.TripApi .internal_static_maps_fleetengine_v1_SearchTripsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.fleetengine.v1.TripApi .internal_static_maps_fleetengine_v1_SearchTripsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.fleetengine.v1.SearchTripsResponse.class, com.google.maps.fleetengine.v1.SearchTripsResponse.Builder.class); } // Construct using com.google.maps.fleetengine.v1.SearchTripsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (tripsBuilder_ == null) { trips_ = java.util.Collections.emptyList(); } else { trips_ = null; tripsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.maps.fleetengine.v1.TripApi .internal_static_maps_fleetengine_v1_SearchTripsResponse_descriptor; } @java.lang.Override public com.google.maps.fleetengine.v1.SearchTripsResponse getDefaultInstanceForType() { return com.google.maps.fleetengine.v1.SearchTripsResponse.getDefaultInstance(); } @java.lang.Override public com.google.maps.fleetengine.v1.SearchTripsResponse build() { com.google.maps.fleetengine.v1.SearchTripsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.maps.fleetengine.v1.SearchTripsResponse buildPartial() { com.google.maps.fleetengine.v1.SearchTripsResponse result = new com.google.maps.fleetengine.v1.SearchTripsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.maps.fleetengine.v1.SearchTripsResponse result) { if (tripsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { trips_ = java.util.Collections.unmodifiableList(trips_); bitField0_ = (bitField0_ & ~0x00000001); } result.trips_ = trips_; } else { result.trips_ = tripsBuilder_.build(); } } private void buildPartial0(com.google.maps.fleetengine.v1.SearchTripsResponse 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.maps.fleetengine.v1.SearchTripsResponse) { return mergeFrom((com.google.maps.fleetengine.v1.SearchTripsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.maps.fleetengine.v1.SearchTripsResponse other) { if (other == com.google.maps.fleetengine.v1.SearchTripsResponse.getDefaultInstance()) return this; if (tripsBuilder_ == null) { if (!other.trips_.isEmpty()) { if (trips_.isEmpty()) { trips_ = other.trips_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTripsIsMutable(); trips_.addAll(other.trips_); } onChanged(); } } else { if (!other.trips_.isEmpty()) { if (tripsBuilder_.isEmpty()) { tripsBuilder_.dispose(); tripsBuilder_ = null; trips_ = other.trips_; bitField0_ = (bitField0_ & ~0x00000001); tripsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTripsFieldBuilder() : null; } else { tripsBuilder_.addAllMessages(other.trips_); } } } 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.maps.fleetengine.v1.Trip m = input.readMessage( com.google.maps.fleetengine.v1.Trip.parser(), extensionRegistry); if (tripsBuilder_ == null) { ensureTripsIsMutable(); trips_.add(m); } else { tripsBuilder_.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.maps.fleetengine.v1.Trip> trips_ = java.util.Collections.emptyList(); private void ensureTripsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { trips_ = new java.util.ArrayList<com.google.maps.fleetengine.v1.Trip>(trips_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.fleetengine.v1.Trip, com.google.maps.fleetengine.v1.Trip.Builder, com.google.maps.fleetengine.v1.TripOrBuilder> tripsBuilder_; /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public java.util.List<com.google.maps.fleetengine.v1.Trip> getTripsList() { if (tripsBuilder_ == null) { return java.util.Collections.unmodifiableList(trips_); } else { return tripsBuilder_.getMessageList(); } } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public int getTripsCount() { if (tripsBuilder_ == null) { return trips_.size(); } else { return tripsBuilder_.getCount(); } } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public com.google.maps.fleetengine.v1.Trip getTrips(int index) { if (tripsBuilder_ == null) { return trips_.get(index); } else { return tripsBuilder_.getMessage(index); } } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder setTrips(int index, com.google.maps.fleetengine.v1.Trip value) { if (tripsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTripsIsMutable(); trips_.set(index, value); onChanged(); } else { tripsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder setTrips( int index, com.google.maps.fleetengine.v1.Trip.Builder builderForValue) { if (tripsBuilder_ == null) { ensureTripsIsMutable(); trips_.set(index, builderForValue.build()); onChanged(); } else { tripsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder addTrips(com.google.maps.fleetengine.v1.Trip value) { if (tripsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTripsIsMutable(); trips_.add(value); onChanged(); } else { tripsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder addTrips(int index, com.google.maps.fleetengine.v1.Trip value) { if (tripsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTripsIsMutable(); trips_.add(index, value); onChanged(); } else { tripsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder addTrips(com.google.maps.fleetengine.v1.Trip.Builder builderForValue) { if (tripsBuilder_ == null) { ensureTripsIsMutable(); trips_.add(builderForValue.build()); onChanged(); } else { tripsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder addTrips( int index, com.google.maps.fleetengine.v1.Trip.Builder builderForValue) { if (tripsBuilder_ == null) { ensureTripsIsMutable(); trips_.add(index, builderForValue.build()); onChanged(); } else { tripsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder addAllTrips( java.lang.Iterable<? extends com.google.maps.fleetengine.v1.Trip> values) { if (tripsBuilder_ == null) { ensureTripsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, trips_); onChanged(); } else { tripsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder clearTrips() { if (tripsBuilder_ == null) { trips_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { tripsBuilder_.clear(); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public Builder removeTrips(int index) { if (tripsBuilder_ == null) { ensureTripsIsMutable(); trips_.remove(index); onChanged(); } else { tripsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public com.google.maps.fleetengine.v1.Trip.Builder getTripsBuilder(int index) { return getTripsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public com.google.maps.fleetengine.v1.TripOrBuilder getTripsOrBuilder(int index) { if (tripsBuilder_ == null) { return trips_.get(index); } else { return tripsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public java.util.List<? extends com.google.maps.fleetengine.v1.TripOrBuilder> getTripsOrBuilderList() { if (tripsBuilder_ != null) { return tripsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(trips_); } } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public com.google.maps.fleetengine.v1.Trip.Builder addTripsBuilder() { return getTripsFieldBuilder() .addBuilder(com.google.maps.fleetengine.v1.Trip.getDefaultInstance()); } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public com.google.maps.fleetengine.v1.Trip.Builder addTripsBuilder(int index) { return getTripsFieldBuilder() .addBuilder(index, com.google.maps.fleetengine.v1.Trip.getDefaultInstance()); } /** * * * <pre> * The list of trips for the requested vehicle. * </pre> * * <code>repeated .maps.fleetengine.v1.Trip trips = 1;</code> */ public java.util.List<com.google.maps.fleetengine.v1.Trip.Builder> getTripsBuilderList() { return getTripsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.fleetengine.v1.Trip, com.google.maps.fleetengine.v1.Trip.Builder, com.google.maps.fleetengine.v1.TripOrBuilder> getTripsFieldBuilder() { if (tripsBuilder_ == null) { tripsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.fleetengine.v1.Trip, com.google.maps.fleetengine.v1.Trip.Builder, com.google.maps.fleetengine.v1.TripOrBuilder>( trips_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); trips_ = null; } return tripsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Pass this token in the SearchTripsRequest to page through list results. The * API returns a trip list on each call, and when no more results remain the * trip list is empty. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:maps.fleetengine.v1.SearchTripsResponse) } // @@protoc_insertion_point(class_scope:maps.fleetengine.v1.SearchTripsResponse) private static final com.google.maps.fleetengine.v1.SearchTripsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.maps.fleetengine.v1.SearchTripsResponse(); } public static com.google.maps.fleetengine.v1.SearchTripsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchTripsResponse> PARSER = new com.google.protobuf.AbstractParser<SearchTripsResponse>() { @java.lang.Override public SearchTripsResponse 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<SearchTripsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchTripsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.maps.fleetengine.v1.SearchTripsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,358
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/UpdateEntryGroupRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataplex/v1/catalog.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * Update EntryGroup Request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateEntryGroupRequest} */ public final class UpdateEntryGroupRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.UpdateEntryGroupRequest) UpdateEntryGroupRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateEntryGroupRequest.newBuilder() to construct. private UpdateEntryGroupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateEntryGroupRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateEntryGroupRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_UpdateEntryGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_UpdateEntryGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.class, com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.Builder.class); } private int bitField0_; public static final int ENTRY_GROUP_FIELD_NUMBER = 1; private com.google.cloud.dataplex.v1.EntryGroup entryGroup_; /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the entryGroup field is set. */ @java.lang.Override public boolean hasEntryGroup() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The entryGroup. */ @java.lang.Override public com.google.cloud.dataplex.v1.EntryGroup getEntryGroup() { return entryGroup_ == null ? com.google.cloud.dataplex.v1.EntryGroup.getDefaultInstance() : entryGroup_; } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dataplex.v1.EntryGroupOrBuilder getEntryGroupOrBuilder() { return entryGroup_ == null ? com.google.cloud.dataplex.v1.EntryGroup.getDefaultInstance() : entryGroup_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. The service validates the request, without performing any * mutations. The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getEntryGroup()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getEntryGroup()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataplex.v1.UpdateEntryGroupRequest)) { return super.equals(obj); } com.google.cloud.dataplex.v1.UpdateEntryGroupRequest other = (com.google.cloud.dataplex.v1.UpdateEntryGroupRequest) obj; if (hasEntryGroup() != other.hasEntryGroup()) return false; if (hasEntryGroup()) { if (!getEntryGroup().equals(other.getEntryGroup())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasEntryGroup()) { hash = (37 * hash) + ENTRY_GROUP_FIELD_NUMBER; hash = (53 * hash) + getEntryGroup().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataplex.v1.UpdateEntryGroupRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Update EntryGroup Request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateEntryGroupRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.UpdateEntryGroupRequest) com.google.cloud.dataplex.v1.UpdateEntryGroupRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_UpdateEntryGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_UpdateEntryGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.class, com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.Builder.class); } // Construct using com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getEntryGroupFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; entryGroup_ = null; if (entryGroupBuilder_ != null) { entryGroupBuilder_.dispose(); entryGroupBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.CatalogProto .internal_static_google_cloud_dataplex_v1_UpdateEntryGroupRequest_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateEntryGroupRequest getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateEntryGroupRequest build() { com.google.cloud.dataplex.v1.UpdateEntryGroupRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateEntryGroupRequest buildPartial() { com.google.cloud.dataplex.v1.UpdateEntryGroupRequest result = new com.google.cloud.dataplex.v1.UpdateEntryGroupRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dataplex.v1.UpdateEntryGroupRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.entryGroup_ = entryGroupBuilder_ == null ? entryGroup_ : entryGroupBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataplex.v1.UpdateEntryGroupRequest) { return mergeFrom((com.google.cloud.dataplex.v1.UpdateEntryGroupRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.UpdateEntryGroupRequest other) { if (other == com.google.cloud.dataplex.v1.UpdateEntryGroupRequest.getDefaultInstance()) return this; if (other.hasEntryGroup()) { mergeEntryGroup(other.getEntryGroup()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getEntryGroupFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.dataplex.v1.EntryGroup entryGroup_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.EntryGroup, com.google.cloud.dataplex.v1.EntryGroup.Builder, com.google.cloud.dataplex.v1.EntryGroupOrBuilder> entryGroupBuilder_; /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the entryGroup field is set. */ public boolean hasEntryGroup() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The entryGroup. */ public com.google.cloud.dataplex.v1.EntryGroup getEntryGroup() { if (entryGroupBuilder_ == null) { return entryGroup_ == null ? com.google.cloud.dataplex.v1.EntryGroup.getDefaultInstance() : entryGroup_; } else { return entryGroupBuilder_.getMessage(); } } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEntryGroup(com.google.cloud.dataplex.v1.EntryGroup value) { if (entryGroupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } entryGroup_ = value; } else { entryGroupBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEntryGroup(com.google.cloud.dataplex.v1.EntryGroup.Builder builderForValue) { if (entryGroupBuilder_ == null) { entryGroup_ = builderForValue.build(); } else { entryGroupBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeEntryGroup(com.google.cloud.dataplex.v1.EntryGroup value) { if (entryGroupBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && entryGroup_ != null && entryGroup_ != com.google.cloud.dataplex.v1.EntryGroup.getDefaultInstance()) { getEntryGroupBuilder().mergeFrom(value); } else { entryGroup_ = value; } } else { entryGroupBuilder_.mergeFrom(value); } if (entryGroup_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearEntryGroup() { bitField0_ = (bitField0_ & ~0x00000001); entryGroup_ = null; if (entryGroupBuilder_ != null) { entryGroupBuilder_.dispose(); entryGroupBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.EntryGroup.Builder getEntryGroupBuilder() { bitField0_ |= 0x00000001; onChanged(); return getEntryGroupFieldBuilder().getBuilder(); } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.EntryGroupOrBuilder getEntryGroupOrBuilder() { if (entryGroupBuilder_ != null) { return entryGroupBuilder_.getMessageOrBuilder(); } else { return entryGroup_ == null ? com.google.cloud.dataplex.v1.EntryGroup.getDefaultInstance() : entryGroup_; } } /** * * * <pre> * Required. EntryGroup Resource. * </pre> * * <code> * .google.cloud.dataplex.v1.EntryGroup entry_group = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.EntryGroup, com.google.cloud.dataplex.v1.EntryGroup.Builder, com.google.cloud.dataplex.v1.EntryGroupOrBuilder> getEntryGroupFieldBuilder() { if (entryGroupBuilder_ == null) { entryGroupBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.EntryGroup, com.google.cloud.dataplex.v1.EntryGroup.Builder, com.google.cloud.dataplex.v1.EntryGroupOrBuilder>( getEntryGroup(), getParentForChildren(), isClean()); entryGroup_ = null; } return entryGroupBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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. Mask of fields to update. * </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_; } private boolean validateOnly_; /** * * * <pre> * Optional. The service validates the request, without performing any * mutations. The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. The service validates the request, without performing any * mutations. The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. The service validates the request, without performing any * mutations. The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataplex.v1.UpdateEntryGroupRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.UpdateEntryGroupRequest) private static final com.google.cloud.dataplex.v1.UpdateEntryGroupRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.UpdateEntryGroupRequest(); } public static com.google.cloud.dataplex.v1.UpdateEntryGroupRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateEntryGroupRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateEntryGroupRequest>() { @java.lang.Override public UpdateEntryGroupRequest 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<UpdateEntryGroupRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateEntryGroupRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateEntryGroupRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
35,588
sulong/projects/com.oracle.truffle.llvm.runtime/src/com/oracle/truffle/llvm/runtime/LLVMLanguage.java
/* * Copyright (c) 2016, 2024, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.truffle.llvm.runtime; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.graalvm.collections.EconomicMap; import org.graalvm.collections.Pair; import org.graalvm.options.OptionDescriptors; import org.graalvm.options.OptionValues; import com.oracle.truffle.api.Assumption; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.ContextThreadLocal; import com.oracle.truffle.api.RootCallTarget; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.TruffleLanguage; import com.oracle.truffle.api.debug.DebuggerTags; import com.oracle.truffle.api.dsl.Idempotent; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.instrumentation.ProvidedTags; import com.oracle.truffle.api.instrumentation.StandardTags; import com.oracle.truffle.api.memory.ByteArraySupport; import com.oracle.truffle.api.nodes.DirectCallNode; import com.oracle.truffle.api.nodes.ExecutableNode; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.llvm.api.Toolchain; import com.oracle.truffle.llvm.runtime.IDGenerater.BitcodeID; import com.oracle.truffle.llvm.runtime.LLVMContext.TLSInitializerAccess; import com.oracle.truffle.llvm.runtime.config.Configuration; import com.oracle.truffle.llvm.runtime.config.Configurations; import com.oracle.truffle.llvm.runtime.config.LLVMCapability; import com.oracle.truffle.llvm.runtime.datalayout.DataLayout; import com.oracle.truffle.llvm.runtime.debug.LLDBSupport; import com.oracle.truffle.llvm.runtime.debug.debugexpr.nodes.DebugExprExecutableNode; import com.oracle.truffle.llvm.runtime.debug.debugexpr.parser.DebugExprException; import com.oracle.truffle.llvm.runtime.debug.debugexpr.parser.antlr.DebugExprParser; import com.oracle.truffle.llvm.runtime.debug.type.LLVMSourceType; import com.oracle.truffle.llvm.runtime.except.LLVMParserException; import com.oracle.truffle.llvm.runtime.except.LLVMUserException; import com.oracle.truffle.llvm.runtime.global.LLVMGlobalContainer; import com.oracle.truffle.llvm.runtime.interop.access.LLVMInteropType; import com.oracle.truffle.llvm.runtime.memory.LLVMMemory; import com.oracle.truffle.llvm.runtime.memory.LLVMMemorySizedOpNode; import com.oracle.truffle.llvm.runtime.memory.LLVMStack; import com.oracle.truffle.llvm.runtime.nodes.api.LLVMStatementNode; import com.oracle.truffle.llvm.runtime.nodes.vars.AggregateTLGlobalInPlaceNode; import com.oracle.truffle.llvm.runtime.pointer.LLVMNativePointer; import com.oracle.truffle.llvm.runtime.pointer.LLVMPointer; import com.oracle.truffle.llvm.runtime.target.TargetTriple; import com.oracle.truffle.llvm.runtime.types.Type; @TruffleLanguage.Registration(id = LLVMLanguage.ID, name = LLVMLanguage.NAME, internal = false, interactive = false, defaultMimeType = LLVMLanguage.LLVM_BITCODE_MIME_TYPE, // byteMimeTypes = {LLVMLanguage.LLVM_BITCODE_MIME_TYPE, LLVMLanguage.LLVM_ELF_SHARED_MIME_TYPE, LLVMLanguage.LLVM_ELF_EXEC_MIME_TYPE, LLVMLanguage.LLVM_MACHO_MIME_TYPE, LLVMLanguage.LLVM_MS_DOS_MIME_TYPE}, // fileTypeDetectors = LLVMFileDetector.class, services = {Toolchain.class}, version = LLVMConfig.VERSION, contextPolicy = TruffleLanguage.ContextPolicy.SHARED, // website = "https://www.graalvm.org/${graalvm-website-version}/reference-manual/llvm/") @ProvidedTags({StandardTags.StatementTag.class, StandardTags.CallTag.class, StandardTags.RootTag.class, StandardTags.RootBodyTag.class, DebuggerTags.AlwaysHalt.class}) public class LLVMLanguage extends TruffleLanguage<LLVMContext> { static final String LLVM_BITCODE_MIME_TYPE = "application/x-llvm-ir-bitcode"; static final String LLVM_BITCODE_EXTENSION = "bc"; static final String LLVM_ELF_SHARED_MIME_TYPE = "application/x-sharedlib"; static final String LLVM_ELF_EXEC_MIME_TYPE = "application/x-executable"; static final String LLVM_ELF_LINUX_EXTENSION = "so"; static final String LLVM_MACHO_MIME_TYPE = "application/x-mach-binary"; static final String LLVM_MS_DOS_MIME_TYPE = "application/x-dosexec"; static final String MAIN_ARGS_KEY = "Sulong Main Args"; static final String PARSE_ONLY_KEY = "Parse only"; public static final String ID = "llvm"; static final String NAME = "LLVM"; @CompilationFinal public boolean singleContext = true; @CompilationFinal private Configuration activeConfiguration = null; private static final class ContextExtensionKey<C extends ContextExtension> extends ContextExtension.Key<C> { private static final ContextExtensionKey<?>[] EMPTY = {}; private final Class<? extends C> clazz; private final int index; private final ContextExtension.Factory<C> factory; ContextExtensionKey(Class<C> clazz, int index, ContextExtension.Factory<C> factory) { this.clazz = clazz; this.index = index; this.factory = factory; } @Override public C get(LLVMContext ctx) { CompilerAsserts.compilationConstant(clazz); return clazz.cast(ctx.getContextExtension(index)); } @SuppressWarnings("unchecked") private <U extends ContextExtension> ContextExtensionKey<U> cast(Class<U> target) { Class<? extends U> c = clazz.asSubclass(target); assert c == clazz; return (ContextExtensionKey<U>) this; } } private ContextExtensionKey<?>[] contextExtensions; @CompilationFinal private LLVMMemory cachedLLVMMemory; @CompilationFinal private ByteArraySupport cachedByteArraySupport; private final EconomicMap<String, LLVMScope> internalFileScopes = EconomicMap.create(); public final ContextThreadLocal<LLVMThreadLocalValue> contextThreadLocal = locals.createContextThreadLocal(LLVMThreadLocalValue::new); static final class LibraryCacheKey { final boolean internal; final String path; private LibraryCacheKey(Source source) { this.internal = source.isInternal(); if (internal) { // internal sources sometimes don't have a path, but their name should be unique String p = source.getPath(); if (p == null) { this.path = source.getName(); } else { this.path = p; } } else { this.path = source.getPath(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (internal ? 1231 : 1237); result = prime * result + ((path == null) ? 0 : path.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } LibraryCacheKey other = (LibraryCacheKey) obj; return this.internal == other.internal && Objects.equals(this.path, other.path); } } static final class LibraryCacheEntry extends WeakReference<CallTarget> { final LibraryCacheKey key; final WeakReference<BitcodeID> id; LibraryCacheEntry(LLVMLanguage language, Source source, CallTarget callTarget, BitcodeID id) { super(callTarget, language.libraryCacheQueue); this.key = new LibraryCacheKey(source); this.id = new WeakReference<>(id); } private boolean isCachable() { return key.path != null; } } private final EconomicMap<LibraryCacheKey, LibraryCacheEntry> libraryCache = EconomicMap.create(); private final ReferenceQueue<CallTarget> libraryCacheQueue = new ReferenceQueue<>(); private final Object libraryCacheLock = new Object(); private final IDGenerater idGenerater = new IDGenerater(); private final LLDBSupport lldbSupport = new LLDBSupport(); private final Assumption noCommonHandleAssumption = Truffle.getRuntime().createAssumption("no common handle"); private final Assumption noDerefHandleAssumption = Truffle.getRuntime().createAssumption("no deref handle"); private final LLVMInteropType.InteropTypeRegistry interopTypeRegistry = new LLVMInteropType.InteropTypeRegistry(); private final ConcurrentHashMap<Class<?>, RootCallTarget> cachedCallTargets = new ConcurrentHashMap<>(); /** * This cache ensures that the truffle cache maintains the default internal libraries, and that * these default internal libraries are not parsed more than once. */ private final EconomicMap<String, Source> defaultInternalLibraryCache = EconomicMap.create(); private DataLayout defaultDataLayout; private TargetTriple defaultTargetTriple; @CompilationFinal private LLVMFunctionCode sulongInitContextCode; @CompilationFinal private LLVMFunction sulongDisposeContext; @CompilationFinal private LLVMFunctionCode startFunctionCode; { /* * This is needed at the moment to make sure the Assumption classes are initialized in the * proper class loader by the time compilation starts. */ noCommonHandleAssumption.isValid(); } public abstract static class Loader implements LLVMCapability { public abstract CallTarget load(LLVMContext context, Source source, BitcodeID id); } @Override protected void initializeContext(LLVMContext context) { if (context.getEnv().isPreInitialization()) { context.initializationDeferred(); } else { context.initialize(createContextExtensions(context.getEnv())); } } public static class LLVMThreadLocalAllocation { private LLVMPointer pointer; private long size; public LLVMThreadLocalAllocation(LLVMPointer pointer, long size) { this.pointer = pointer; this.size = size; } public LLVMPointer getPointer() { return pointer; } public long getSize() { return size; } } public static class LLVMThreadLocalValue { final LLVMContext context; LLVMThreadLocalAllocation[] sections = new LLVMThreadLocalAllocation[10]; final WeakReference<Thread> thread; boolean isDisposed; LLVMStack stack; LLVMPointer localStorage; LLVMGlobalContainer[][] globalContainers = new LLVMGlobalContainer[10][]; List<LLVMUserException> exceptionStack = new ArrayList<>(); LLVMThreadLocalValue(LLVMContext context, Thread thread) { this.context = context; this.thread = new WeakReference<>(thread); isDisposed = false; localStorage = LLVMNativePointer.createNull(); } public void addSection(LLVMPointer sectionBase, long size, BitcodeID bitcodeID) { assert sectionBase != null; assert size > 0; int index = bitcodeID.getId(); if (index >= sections.length) { int newLength = (index + 1) + ((index + 1) / 2); sections = Arrays.copyOf(sections, newLength); } sections[index] = new LLVMThreadLocalAllocation(sectionBase, size); } public LLVMThreadLocalAllocation getSection(BitcodeID bitcodeID) { int index = bitcodeID.getId(); // if index is out of range, then it does not have a TL section return index < sections.length ? sections[index] : null; } public LLVMPointer getSectionBase(BitcodeID bitcodeID) { LLVMThreadLocalAllocation section = getSection(bitcodeID); return section == null ? null : section.getPointer(); } public void setDisposed() { isDisposed = true; } public boolean isDisposed() { return isDisposed; } public LLVMPointer getThreadLocalStorage() { return localStorage; } public void setThreadLocalStorage(LLVMPointer value) { localStorage = value; } public void removeThreadLocalStorage() { localStorage = LLVMNativePointer.createNull(); } public LLVMStack getLLVMStack() { return stack; } public void pushException(LLVMUserException exception) { exceptionStack.add(exception); } public LLVMUserException popException() { return exceptionStack.remove(exceptionStack.size() - 1); } public boolean hasException() { return !exceptionStack.isEmpty(); } public void setLLVMStack(LLVMStack stack) { assert this.stack == null; this.stack = stack; } public LLVMStack removeLLVMStack() { LLVMStack tmp = stack; this.stack = null; return tmp; } public void addGlobalContainer(LLVMGlobalContainer[] globalContainer, BitcodeID bitcodeID) { int id = bitcodeID.getId(); if (id >= globalContainers.length) { int newLength = (id + 1) + ((id + 1) / 2); globalContainers = Arrays.copyOf(globalContainers, newLength); } globalContainers[id] = globalContainer; } public LLVMGlobalContainer getGlobalContainer(int index, BitcodeID bitcodeID) { int id = bitcodeID.getId(); assert 0 < id && id < globalContainers.length; assert 0 < index && index < globalContainers[id].length; return globalContainers[id][index]; } } private ContextExtension[] createContextExtensions(Env env) { ContextExtension[] ctxExts = new ContextExtension[contextExtensions.length]; for (int i = 0; i < contextExtensions.length; i++) { ContextExtensionKey<?> key = contextExtensions[i]; ContextExtension ext = key.factory.create(env); ctxExts[i] = key.clazz.cast(ext); // fail early if the factory returns a wrong class } return ctxExts; } /** * Do not use this on fast-path. */ public static LLVMContext getContext() { CompilerAsserts.neverPartOfCompilation("Use faster context lookup methods for the fast-path."); return LLVMContext.get(null); } private static final LanguageReference<LLVMLanguage> REFERENCE = LanguageReference.create(LLVMLanguage.class); public static LLVMLanguage get(Node node) { return REFERENCE.get(node); } @Override protected void initializeThread(LLVMContext context, Thread thread) { getCapability(PlatformCapability.class).initializeThread(context, thread); try (TLSInitializerAccess access = context.getTLSInitializerAccess(true)) { // need to duplicate the thread local globals for this thread. for (AggregateTLGlobalInPlaceNode globalInitializer : access.getThreadLocalGlobalInitializer()) { // TODO: use the call target of AggregateTLGlobalInPlaceNode, rather than the node // itself (GR-37471). globalInitializer.executeWithThread(null, thread); } access.registerLiveThread(thread); } } public static CallTarget getLLDBLoadFunction(Type type) { LLVMLanguage language = get(null); return language.lldbSupport.getLoadFunction(language, type); } public <C extends LLVMCapability> C getCapability(Class<C> type) { CompilerAsserts.partialEvaluationConstant(type); if (type == LLVMMemory.class) { return type.cast(getLLVMMemory()); } else { C ret = activeConfiguration.getCapability(type); if (CompilerDirectives.isPartialEvaluationConstant(this)) { CompilerAsserts.partialEvaluationConstant(ret); } return ret; } } /** * This function will return an assumption that is valid as long as no normal handles have been * created. */ public Assumption getNoCommonHandleAssumption() { return noCommonHandleAssumption; } /** * This function will return an assumption that is valid as long as no deref handles have been * created. */ public Assumption getNoDerefHandleAssumption() { return noDerefHandleAssumption; } public final String getLLVMLanguageHome() { return getLanguageHome(); } public Configuration getActiveConfiguration() { if (activeConfiguration != null) { return activeConfiguration; } throw new IllegalStateException("No context, please create the context before accessing the configuration."); } public LLVMMemory getLLVMMemory() { assert cachedLLVMMemory != null; return cachedLLVMMemory; } public ByteArraySupport getByteArraySupport() { assert cachedByteArraySupport != null; return cachedByteArraySupport; } public LLVMScope getInternalFileScopes(String libraryName) { return internalFileScopes.get(libraryName); } public void addInternalFileScope(String libraryName, LLVMScope scope) { internalFileScopes.put(libraryName, scope); } public boolean isDefaultInternalLibraryCacheEmpty() { return defaultInternalLibraryCache.isEmpty(); } public void setDefaultInternalLibraryCache(Source library) { defaultInternalLibraryCache.put(library.getName(), library); } @Override protected LLVMContext createContext(Env env) { ensureActiveConfiguration(env); Toolchain toolchain = new ToolchainImpl(activeConfiguration.getCapability(ToolchainConfig.class), this); env.registerService(toolchain); LLVMContext context = new LLVMContext(this, env, toolchain); return context; } private synchronized void ensureActiveConfiguration(Env env) { if (activeConfiguration == null) { final ArrayList<ContextExtension.Key<?>> ctxExts = new ArrayList<>(); ContextExtension.Registry r = new ContextExtension.Registry() { private int count; @Override public <C extends ContextExtension> ContextExtension.Key<C> register(Class<C> type, ContextExtension.Factory<C> factory) { ContextExtension.Key<C> key = new ContextExtensionKey<>(type, count++, factory); ctxExts.add(key); assert count == ctxExts.size(); return key; } }; activeConfiguration = Configurations.createConfiguration(this, r, env.getOptions()); cachedLLVMMemory = activeConfiguration.getCapability(LLVMMemory.class); ByteOrder order = activeConfiguration.getCapability(PlatformCapability.class).getPlatformByteOrder(); if (order == ByteOrder.LITTLE_ENDIAN) { cachedByteArraySupport = ByteArraySupport.littleEndian(); } else if (order == ByteOrder.BIG_ENDIAN) { cachedByteArraySupport = ByteArraySupport.bigEndian(); } else { throw new IllegalStateException("unexpected byte order " + order); } contextExtensions = ctxExts.toArray(ContextExtensionKey.EMPTY); } } /** * Find a context extension key, that can be used to retrieve a context extension instance. This * method must not be called from the fast-path. The return value is safe to be cached across * contexts in a single engine. */ public <C extends ContextExtension> ContextExtension.Key<C> lookupContextExtension(Class<C> type) { CompilerAsserts.neverPartOfCompilation(); for (ContextExtensionKey<?> key : contextExtensions) { if (type == key.clazz) { return key.cast(type); } } return null; } @Override protected ExecutableNode parse(InlineParsingRequest request) { Object globalScope = getScope(getContext()); final DebugExprParser d = new DebugExprParser(request, globalScope); try { return new DebugExprExecutableNode(d.parse()); } catch (DebugExprException | LLVMParserException e) { // error found during parsing String errorMessage = e.getMessage(); return new ExecutableNode(this) { @Override public Object execute(VirtualFrame frame) { return errorMessage; } }; } } @Override protected boolean patchContext(LLVMContext context, Env newEnv) { boolean compatible = Configurations.areOptionsCompatible(context.getEnv().getOptions(), newEnv.getOptions()); if (!compatible) { return false; } return context.patchContext(newEnv, createContextExtensions(newEnv)); } @Override protected boolean areOptionsCompatible(OptionValues firstOptions, OptionValues newOptions) { return Configurations.areOptionsCompatible(firstOptions, newOptions); } @Override protected void exitContext(LLVMContext context, ExitMode exitMode, int exitCode) { context.exitContext(sulongDisposeContext); } @Override protected void finalizeContext(LLVMContext context) { context.finalizeContext(); } @Override protected void disposeContext(LLVMContext context) { context.dispose(); } static class FreeGlobalsNode extends RootNode { @Child LLVMMemorySizedOpNode freeNode; FreeGlobalsNode(LLVMLanguage language, NodeFactory nodeFactory) { super(language); this.freeNode = nodeFactory.createFreeGlobalsBlock(); } @Override public Object execute(VirtualFrame frame) { // Executed in dispose(), therefore can read unsynchronized LLVMContext context = LLVMContext.get(this); for (int i = 0; i < context.globalsBlockStore.size(); i++) { Pair<LLVMPointer, Long> store = getElement(context.globalsBlockStore, i); if (store != null) { freeNode.doPair(store); } } return null; } @TruffleBoundary(allowInlining = true) private static <T> T getElement(EconomicMap<Integer, T> list, int idx) { return list.get(idx); } } public void freeThreadLocalGlobal(LLVMThreadLocalValue threadLocalValue) { if (threadLocalValue != null) { synchronized (threadLocalValue) { if (!threadLocalValue.isDisposed()) { for (LLVMThreadLocalAllocation section : threadLocalValue.sections) { if (section != null) { freeOpNode.execute(section.getPointer(), section.getSize()); } } for (LLVMGlobalContainer[] globalContainers : threadLocalValue.globalContainers) { if (globalContainers != null) { for (LLVMGlobalContainer globalContainer : globalContainers) { if (globalContainer != null) { globalContainer.dispose(); } } } } threadLocalValue.setDisposed(); } } } } abstract static class InitializeContextNode extends LLVMStatementNode { @Child private DirectCallNode initContext; InitializeContextNode(LLVMFunctionCode initContextFunctionCode) { RootCallTarget initContextFunction = initContextFunctionCode.getLLVMIRFunctionSlowPath(); this.initContext = DirectCallNode.create(initContextFunction); } @Specialization public void doInit() { LLVMContext ctx = LLVMContext.get(this); if (!ctx.initialized) { assert !ctx.cleanupNecessary; ctx.initialized = true; ctx.cleanupNecessary = true; Object[] args = new Object[]{ctx.getThreadingStack().getStack(this), ctx.getApplicationArguments(), LLVMContext.getEnvironmentVariables(), LLVMContext.getRandomValues()}; initContext.call(args); } } } public void setSulongInitContext(LLVMFunction function) { this.sulongInitContextCode = new LLVMFunctionCode(function); } public void setSulongDisposeContext(LLVMFunction function) { this.sulongDisposeContext = function; } public void setStartFunctionCode(LLVMFunctionCode startFunctionCode) { this.startFunctionCode = startFunctionCode; } public LLVMFunctionCode getStartFunctionCode() { assert startFunctionCode != null; return startFunctionCode; } private CallTarget freeGlobalBlocks; private LLVMMemorySizedOpNode freeOpNode; protected void initFreeGlobalBlocks(NodeFactory nodeFactory) { // lazily initialized, this is not necessary if there are no global blocks allocated if (freeGlobalBlocks == null) { freeGlobalBlocks = new FreeGlobalsNode(this, nodeFactory).getCallTarget(); } if (freeOpNode == null) { freeOpNode = nodeFactory.getFreeGlobalsBlockUncached(); } } public CallTarget getFreeGlobalBlocks() { return freeGlobalBlocks; } public synchronized void setDefaultBitcode(DataLayout datalayout, TargetTriple targetTriple) { // Libsulong datalayout can only be set once. if (defaultDataLayout == null) { this.defaultDataLayout = datalayout; } else { throw new IllegalStateException("The default datalayout cannot be overwritten"); } // Libsulong targettriple can only be set once. if (defaultTargetTriple == null) { this.defaultTargetTriple = targetTriple; } else { throw new IllegalStateException("The default targetTriple cannot be overwritten"); } } public DataLayout getDefaultDataLayout() { return defaultDataLayout; } public TargetTriple getDefaultTargetTriple() { return defaultTargetTriple; } @TruffleBoundary public LLVMInteropType getInteropType(LLVMSourceType sourceType) { return interopTypeRegistry.get(sourceType); } public LLVMStatementNode createInitializeContextNode() { // we can't do the initialization in the LLVMContext constructor nor in // Sulong.createContext() because Truffle is not properly initialized there. So, we need to // do it in a delayed way. if (sulongInitContextCode == null) { throw new IllegalStateException("Context cannot be initialized:" + LLVMContext.SULONG_INIT_CONTEXT + " was not found"); } return LLVMLanguageFactory.InitializeContextNodeGen.create(sulongInitContextCode); } /** * If a library has already been parsed, the call target will be retrieved from the language * cache. * * @param request request for parsing * @return calltarget of the library */ @Override protected CallTarget parse(ParsingRequest request) { if (LLVMContext.get(null).getEnv().isPreInitialization()) { throw new UnsupportedOperationException("Parsing not supported during context pre-initialization"); } Source source = request.getSource(); if (source.isCached()) { synchronized (libraryCacheLock) { CallTarget cached = getCachedLibrary(source); if (cached == null) { BitcodeID id = idGenerater.generateID(source.getName()); cached = getCapability(Loader.class).load(getContext(), source, id); LibraryCacheEntry entry = new LibraryCacheEntry(this, source, cached, id); if (entry.isCachable()) { assert !libraryCache.containsKey(entry.key) : "racy insertion despite lock?"; libraryCache.put(entry.key, entry); } } return cached; } } else { // just get the id here and give it to the parserDriver return getCapability(Loader.class).load(getContext(), source, idGenerater.generateID(source.getName())); } } private void lazyCacheCleanup() { /* * Just lazily clean up one entry. We do this on every lookup. Under the assumption that * lookups are more frequent than insertions, this will eventually catch up and remove every * GCed entry. */ LibraryCacheEntry ref = (LibraryCacheEntry) libraryCacheQueue.poll(); if (ref != null) { if (LibraryLocator.loggingEnabled()) { LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage lazy cached clean up, entry", ref.key.path); BitcodeID bitcodeID = ref.id.get(); if (bitcodeID != null) { LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage lazy cached clean up, bitcode id name", bitcodeID.getName()); LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage lazy cached clean up, bitcode id", bitcodeID.getId()); } else { LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage lazy cached clean up, bitcode id", bitcodeID); } } if (libraryCache.get(ref.key) == ref) { libraryCache.removeKey(ref.key); } } } @TruffleBoundary public CallTarget getCachedLibrary(Source source) { synchronized (libraryCacheLock) { lazyCacheCleanup(); LibraryCacheKey key = new LibraryCacheKey(source); LibraryCacheEntry entry = libraryCache.get(key); if (LibraryLocator.loggingEnabled()) { LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage get cached library, source name", source.getName()); LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage get cached library, source", source); LibraryLocator.traceStaticInits(getContext(), "LLVMLanguage get cached library, entry", entry); } if (entry == null) { return null; } assert entry.key.equals(key); CallTarget ret = entry.get(); if (ret == null) { // clean up the map after an entry has been cleared by the GC libraryCache.removeKey(entry.key); } return ret; } } @Override protected Object getScope(LLVMContext context) { return context.getGlobalScopeChain(); } @Override protected OptionDescriptors getOptionDescriptors() { return Configurations.getOptionDescriptors(); } @Override protected boolean isThreadAccessAllowed(Thread thread, boolean singleThreaded) { return true; } @Override protected void disposeThread(LLVMContext context, Thread thread) { getCapability(PlatformCapability.class).disposeThread(context, thread); disposeThreadNoGuestCode(context, thread); } /** * Disposes thread-specific resources (e.g. the thread's stack, thread-local storage, etc). This * method may call a native helper function via NFI but will not call arbitrary guest code. It * is therefore safe to run this method while thread-local * {@link com.oracle.truffle.api.TruffleSafepoint} actions are disabled. */ protected void disposeThreadNoGuestCode(LLVMContext context, Thread thread) { super.disposeThread(context, thread); if (context.isInitialized()) { context.getThreadingStack().freeStack(getLLVMMemory(), thread); } LLVMThreadLocalValue threadLocalValue = this.contextThreadLocal.get(context.getEnv().getContext(), thread); threadLocalValue.removeThreadLocalStorage(); if (!threadLocalValue.isDisposed()) { freeThreadLocalGlobal(threadLocalValue); } try (TLSInitializerAccess access = context.getTLSInitializerAccess(false)) { access.unregisterLiveThread(thread); } } @Override protected void initializeMultipleContexts() { super.initializeMultipleContexts(); singleContext = false; } public RootCallTarget createCachedCallTarget(Class<?> key, Function<LLVMLanguage, RootNode> create) { return cachedCallTargets.computeIfAbsent(key, k -> create.apply(LLVMLanguage.this).getCallTarget()); } @Idempotent public static boolean isSingleContext(Node node) { return LLVMLanguage.get(node).singleContext; } }
googleads/google-ads-java
35,453
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/enums/ExternalConversionSourceEnum.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/enums/external_conversion_source.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.enums; /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v19.enums.ExternalConversionSourceEnum} */ public final class ExternalConversionSourceEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.enums.ExternalConversionSourceEnum) ExternalConversionSourceEnumOrBuilder { private static final long serialVersionUID = 0L; // Use ExternalConversionSourceEnum.newBuilder() to construct. private ExternalConversionSourceEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExternalConversionSourceEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ExternalConversionSourceEnum(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v19_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v19_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.Builder.class); } /** * <pre> * The external conversion source that is associated with a ConversionAction. * </pre> * * Protobuf enum {@code google.ads.googleads.v19.enums.ExternalConversionSourceEnum.ExternalConversionSource} */ public enum ExternalConversionSource implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ WEBPAGE(2), /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ ANALYTICS(3), /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ UPLOAD(4), /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ AD_CALL_METRICS(5), /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ WEBSITE_CALL_METRICS(6), /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ STORE_VISITS(7), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ ANDROID_IN_APP(8), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ IOS_IN_APP(9), /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ IOS_FIRST_OPEN(10), /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ APP_UNSPECIFIED(11), /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ ANDROID_FIRST_OPEN(12), /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ UPLOAD_CALLS(13), /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ FIREBASE(14), /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ CLICK_TO_CALL(15), /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ SALESFORCE(16), /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ STORE_SALES_CRM(17), /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ STORE_SALES_PAYMENT_NETWORK(18), /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ GOOGLE_PLAY(19), /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ THIRD_PARTY_APP_ANALYTICS(20), /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ GOOGLE_ATTRIBUTION(21), /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ STORE_SALES_DIRECT_UPLOAD(23), /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ STORE_SALES(24), /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ SEARCH_ADS_360(25), /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ GOOGLE_HOSTED(27), /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ FLOODLIGHT(29), /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ ANALYTICS_SEARCH_ADS_360(31), /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ FIREBASE_SEARCH_ADS_360(33), /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ DISPLAY_AND_VIDEO_360_FLOODLIGHT(34), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ public static final int WEBPAGE_VALUE = 2; /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ public static final int ANALYTICS_VALUE = 3; /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ public static final int UPLOAD_VALUE = 4; /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ public static final int AD_CALL_METRICS_VALUE = 5; /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ public static final int WEBSITE_CALL_METRICS_VALUE = 6; /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ public static final int STORE_VISITS_VALUE = 7; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ public static final int ANDROID_IN_APP_VALUE = 8; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ public static final int IOS_IN_APP_VALUE = 9; /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ public static final int IOS_FIRST_OPEN_VALUE = 10; /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ public static final int APP_UNSPECIFIED_VALUE = 11; /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ public static final int ANDROID_FIRST_OPEN_VALUE = 12; /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ public static final int UPLOAD_CALLS_VALUE = 13; /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ public static final int FIREBASE_VALUE = 14; /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ public static final int CLICK_TO_CALL_VALUE = 15; /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ public static final int SALESFORCE_VALUE = 16; /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ public static final int STORE_SALES_CRM_VALUE = 17; /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ public static final int STORE_SALES_PAYMENT_NETWORK_VALUE = 18; /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ public static final int GOOGLE_PLAY_VALUE = 19; /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ public static final int THIRD_PARTY_APP_ANALYTICS_VALUE = 20; /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ public static final int GOOGLE_ATTRIBUTION_VALUE = 21; /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ public static final int STORE_SALES_DIRECT_UPLOAD_VALUE = 23; /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ public static final int STORE_SALES_VALUE = 24; /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ public static final int SEARCH_ADS_360_VALUE = 25; /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ public static final int GOOGLE_HOSTED_VALUE = 27; /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ public static final int FLOODLIGHT_VALUE = 29; /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ public static final int ANALYTICS_SEARCH_ADS_360_VALUE = 31; /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ public static final int FIREBASE_SEARCH_ADS_360_VALUE = 33; /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ public static final int DISPLAY_AND_VIDEO_360_FLOODLIGHT_VALUE = 34; 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 ExternalConversionSource 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 ExternalConversionSource forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return WEBPAGE; case 3: return ANALYTICS; case 4: return UPLOAD; case 5: return AD_CALL_METRICS; case 6: return WEBSITE_CALL_METRICS; case 7: return STORE_VISITS; case 8: return ANDROID_IN_APP; case 9: return IOS_IN_APP; case 10: return IOS_FIRST_OPEN; case 11: return APP_UNSPECIFIED; case 12: return ANDROID_FIRST_OPEN; case 13: return UPLOAD_CALLS; case 14: return FIREBASE; case 15: return CLICK_TO_CALL; case 16: return SALESFORCE; case 17: return STORE_SALES_CRM; case 18: return STORE_SALES_PAYMENT_NETWORK; case 19: return GOOGLE_PLAY; case 20: return THIRD_PARTY_APP_ANALYTICS; case 21: return GOOGLE_ATTRIBUTION; case 23: return STORE_SALES_DIRECT_UPLOAD; case 24: return STORE_SALES; case 25: return SEARCH_ADS_360; case 27: return GOOGLE_HOSTED; case 29: return FLOODLIGHT; case 31: return ANALYTICS_SEARCH_ADS_360; case 33: return FIREBASE_SEARCH_ADS_360; case 34: return DISPLAY_AND_VIDEO_360_FLOODLIGHT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ExternalConversionSource> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource>() { public ExternalConversionSource findValueByNumber(int number) { return ExternalConversionSource.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.ads.googleads.v19.enums.ExternalConversionSourceEnum.getDescriptor().getEnumTypes().get(0); } private static final ExternalConversionSource[] VALUES = values(); public static ExternalConversionSource 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 ExternalConversionSource(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v19.enums.ExternalConversionSourceEnum.ExternalConversionSource) } 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 { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; 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.enums.ExternalConversionSourceEnum)) { return super.equals(obj); } com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum other = (com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum) obj; 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 = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v19.enums.ExternalConversionSourceEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.enums.ExternalConversionSourceEnum) com.google.ads.googleads.v19.enums.ExternalConversionSourceEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v19_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v19_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.Builder.class); } // Construct using com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v19_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum build() { com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum buildPartial() { com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum result = new com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum(this); onBuilt(); return result; } @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.enums.ExternalConversionSourceEnum) { return mergeFrom((com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum other) { if (other == com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum.getDefaultInstance()) return this; 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; 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; } @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.enums.ExternalConversionSourceEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.enums.ExternalConversionSourceEnum) private static final com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum(); } public static com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExternalConversionSourceEnum> PARSER = new com.google.protobuf.AbstractParser<ExternalConversionSourceEnum>() { @java.lang.Override public ExternalConversionSourceEnum 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<ExternalConversionSourceEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExternalConversionSourceEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,453
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/enums/ExternalConversionSourceEnum.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/enums/external_conversion_source.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.enums; /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v20.enums.ExternalConversionSourceEnum} */ public final class ExternalConversionSourceEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.enums.ExternalConversionSourceEnum) ExternalConversionSourceEnumOrBuilder { private static final long serialVersionUID = 0L; // Use ExternalConversionSourceEnum.newBuilder() to construct. private ExternalConversionSourceEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExternalConversionSourceEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ExternalConversionSourceEnum(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v20_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v20_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.Builder.class); } /** * <pre> * The external conversion source that is associated with a ConversionAction. * </pre> * * Protobuf enum {@code google.ads.googleads.v20.enums.ExternalConversionSourceEnum.ExternalConversionSource} */ public enum ExternalConversionSource implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ WEBPAGE(2), /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ ANALYTICS(3), /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ UPLOAD(4), /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ AD_CALL_METRICS(5), /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ WEBSITE_CALL_METRICS(6), /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ STORE_VISITS(7), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ ANDROID_IN_APP(8), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ IOS_IN_APP(9), /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ IOS_FIRST_OPEN(10), /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ APP_UNSPECIFIED(11), /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ ANDROID_FIRST_OPEN(12), /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ UPLOAD_CALLS(13), /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ FIREBASE(14), /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ CLICK_TO_CALL(15), /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ SALESFORCE(16), /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ STORE_SALES_CRM(17), /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ STORE_SALES_PAYMENT_NETWORK(18), /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ GOOGLE_PLAY(19), /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ THIRD_PARTY_APP_ANALYTICS(20), /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ GOOGLE_ATTRIBUTION(21), /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ STORE_SALES_DIRECT_UPLOAD(23), /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ STORE_SALES(24), /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ SEARCH_ADS_360(25), /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ GOOGLE_HOSTED(27), /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ FLOODLIGHT(29), /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ ANALYTICS_SEARCH_ADS_360(31), /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ FIREBASE_SEARCH_ADS_360(33), /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ DISPLAY_AND_VIDEO_360_FLOODLIGHT(34), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ public static final int WEBPAGE_VALUE = 2; /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ public static final int ANALYTICS_VALUE = 3; /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ public static final int UPLOAD_VALUE = 4; /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ public static final int AD_CALL_METRICS_VALUE = 5; /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ public static final int WEBSITE_CALL_METRICS_VALUE = 6; /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ public static final int STORE_VISITS_VALUE = 7; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ public static final int ANDROID_IN_APP_VALUE = 8; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ public static final int IOS_IN_APP_VALUE = 9; /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ public static final int IOS_FIRST_OPEN_VALUE = 10; /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ public static final int APP_UNSPECIFIED_VALUE = 11; /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ public static final int ANDROID_FIRST_OPEN_VALUE = 12; /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ public static final int UPLOAD_CALLS_VALUE = 13; /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ public static final int FIREBASE_VALUE = 14; /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ public static final int CLICK_TO_CALL_VALUE = 15; /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ public static final int SALESFORCE_VALUE = 16; /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ public static final int STORE_SALES_CRM_VALUE = 17; /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ public static final int STORE_SALES_PAYMENT_NETWORK_VALUE = 18; /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ public static final int GOOGLE_PLAY_VALUE = 19; /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ public static final int THIRD_PARTY_APP_ANALYTICS_VALUE = 20; /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ public static final int GOOGLE_ATTRIBUTION_VALUE = 21; /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ public static final int STORE_SALES_DIRECT_UPLOAD_VALUE = 23; /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ public static final int STORE_SALES_VALUE = 24; /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ public static final int SEARCH_ADS_360_VALUE = 25; /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ public static final int GOOGLE_HOSTED_VALUE = 27; /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ public static final int FLOODLIGHT_VALUE = 29; /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ public static final int ANALYTICS_SEARCH_ADS_360_VALUE = 31; /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ public static final int FIREBASE_SEARCH_ADS_360_VALUE = 33; /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ public static final int DISPLAY_AND_VIDEO_360_FLOODLIGHT_VALUE = 34; 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 ExternalConversionSource 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 ExternalConversionSource forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return WEBPAGE; case 3: return ANALYTICS; case 4: return UPLOAD; case 5: return AD_CALL_METRICS; case 6: return WEBSITE_CALL_METRICS; case 7: return STORE_VISITS; case 8: return ANDROID_IN_APP; case 9: return IOS_IN_APP; case 10: return IOS_FIRST_OPEN; case 11: return APP_UNSPECIFIED; case 12: return ANDROID_FIRST_OPEN; case 13: return UPLOAD_CALLS; case 14: return FIREBASE; case 15: return CLICK_TO_CALL; case 16: return SALESFORCE; case 17: return STORE_SALES_CRM; case 18: return STORE_SALES_PAYMENT_NETWORK; case 19: return GOOGLE_PLAY; case 20: return THIRD_PARTY_APP_ANALYTICS; case 21: return GOOGLE_ATTRIBUTION; case 23: return STORE_SALES_DIRECT_UPLOAD; case 24: return STORE_SALES; case 25: return SEARCH_ADS_360; case 27: return GOOGLE_HOSTED; case 29: return FLOODLIGHT; case 31: return ANALYTICS_SEARCH_ADS_360; case 33: return FIREBASE_SEARCH_ADS_360; case 34: return DISPLAY_AND_VIDEO_360_FLOODLIGHT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ExternalConversionSource> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource>() { public ExternalConversionSource findValueByNumber(int number) { return ExternalConversionSource.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.ads.googleads.v20.enums.ExternalConversionSourceEnum.getDescriptor().getEnumTypes().get(0); } private static final ExternalConversionSource[] VALUES = values(); public static ExternalConversionSource 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 ExternalConversionSource(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v20.enums.ExternalConversionSourceEnum.ExternalConversionSource) } 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 { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; 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.enums.ExternalConversionSourceEnum)) { return super.equals(obj); } com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum other = (com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum) obj; 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 = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v20.enums.ExternalConversionSourceEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.enums.ExternalConversionSourceEnum) com.google.ads.googleads.v20.enums.ExternalConversionSourceEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v20_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v20_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.Builder.class); } // Construct using com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v20_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum build() { com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum buildPartial() { com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum result = new com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum(this); onBuilt(); return result; } @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.enums.ExternalConversionSourceEnum) { return mergeFrom((com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum other) { if (other == com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum.getDefaultInstance()) return this; 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; 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; } @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.enums.ExternalConversionSourceEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.enums.ExternalConversionSourceEnum) private static final com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum(); } public static com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExternalConversionSourceEnum> PARSER = new com.google.protobuf.AbstractParser<ExternalConversionSourceEnum>() { @java.lang.Override public ExternalConversionSourceEnum 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<ExternalConversionSourceEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExternalConversionSourceEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,453
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/enums/ExternalConversionSourceEnum.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/enums/external_conversion_source.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.enums; /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v21.enums.ExternalConversionSourceEnum} */ public final class ExternalConversionSourceEnum extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.enums.ExternalConversionSourceEnum) ExternalConversionSourceEnumOrBuilder { private static final long serialVersionUID = 0L; // Use ExternalConversionSourceEnum.newBuilder() to construct. private ExternalConversionSourceEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExternalConversionSourceEnum() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ExternalConversionSourceEnum(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v21_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v21_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.Builder.class); } /** * <pre> * The external conversion source that is associated with a ConversionAction. * </pre> * * Protobuf enum {@code google.ads.googleads.v21.enums.ExternalConversionSourceEnum.ExternalConversionSource} */ public enum ExternalConversionSource implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ UNSPECIFIED(0), /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ UNKNOWN(1), /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ WEBPAGE(2), /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ ANALYTICS(3), /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ UPLOAD(4), /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ AD_CALL_METRICS(5), /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ WEBSITE_CALL_METRICS(6), /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ STORE_VISITS(7), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ ANDROID_IN_APP(8), /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ IOS_IN_APP(9), /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ IOS_FIRST_OPEN(10), /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ APP_UNSPECIFIED(11), /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ ANDROID_FIRST_OPEN(12), /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ UPLOAD_CALLS(13), /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ FIREBASE(14), /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ CLICK_TO_CALL(15), /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ SALESFORCE(16), /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ STORE_SALES_CRM(17), /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ STORE_SALES_PAYMENT_NETWORK(18), /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ GOOGLE_PLAY(19), /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ THIRD_PARTY_APP_ANALYTICS(20), /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ GOOGLE_ATTRIBUTION(21), /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ STORE_SALES_DIRECT_UPLOAD(23), /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ STORE_SALES(24), /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ SEARCH_ADS_360(25), /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ GOOGLE_HOSTED(27), /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ FLOODLIGHT(29), /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ ANALYTICS_SEARCH_ADS_360(31), /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ FIREBASE_SEARCH_ADS_360(33), /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ DISPLAY_AND_VIDEO_360_FLOODLIGHT(34), UNRECOGNIZED(-1), ; /** * <pre> * Not specified. * </pre> * * <code>UNSPECIFIED = 0;</code> */ public static final int UNSPECIFIED_VALUE = 0; /** * <pre> * Represents value unknown in this version. * </pre> * * <code>UNKNOWN = 1;</code> */ public static final int UNKNOWN_VALUE = 1; /** * <pre> * Conversion that occurs when a user navigates to a particular webpage * after viewing an ad; Displayed in Google Ads UI as 'Website'. * </pre> * * <code>WEBPAGE = 2;</code> */ public static final int WEBPAGE_VALUE = 2; /** * <pre> * Conversion that comes from linked Google Analytics goal or transaction; * Displayed in Google Ads UI as 'Analytics'. * </pre> * * <code>ANALYTICS = 3;</code> */ public static final int ANALYTICS_VALUE = 3; /** * <pre> * Website conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from clicks'. * </pre> * * <code>UPLOAD = 4;</code> */ public static final int UPLOAD_VALUE = 4; /** * <pre> * Conversion that occurs when a user clicks on a call extension directly on * an ad; Displayed in Google Ads UI as 'Calls from ads'. * </pre> * * <code>AD_CALL_METRICS = 5;</code> */ public static final int AD_CALL_METRICS_VALUE = 5; /** * <pre> * Conversion that occurs when a user calls a dynamically-generated phone * number (by installed javascript) from an advertiser's website after * clicking on an ad; Displayed in Google Ads UI as 'Calls from website'. * </pre> * * <code>WEBSITE_CALL_METRICS = 6;</code> */ public static final int WEBSITE_CALL_METRICS_VALUE = 6; /** * <pre> * Conversion that occurs when a user visits an advertiser's retail store * after clicking on a Google ad; * Displayed in Google Ads UI as 'Store visits'. * </pre> * * <code>STORE_VISITS = 7;</code> */ public static final int STORE_VISITS_VALUE = 7; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an Android app; * Displayed in Google Ads UI as 'Android in-app action'. * </pre> * * <code>ANDROID_IN_APP = 8;</code> */ public static final int ANDROID_IN_APP_VALUE = 8; /** * <pre> * Conversion that occurs when a user takes an in-app action such as a * purchase in an iOS app; * Displayed in Google Ads UI as 'iOS in-app action'. * </pre> * * <code>IOS_IN_APP = 9;</code> */ public static final int IOS_IN_APP_VALUE = 9; /** * <pre> * Conversion that occurs when a user opens an iOS app for the first time; * Displayed in Google Ads UI as 'iOS app install (first open)'. * </pre> * * <code>IOS_FIRST_OPEN = 10;</code> */ public static final int IOS_FIRST_OPEN_VALUE = 10; /** * <pre> * Legacy app conversions that do not have an AppPlatform provided; * Displayed in Google Ads UI as 'Mobile app'. * </pre> * * <code>APP_UNSPECIFIED = 11;</code> */ public static final int APP_UNSPECIFIED_VALUE = 11; /** * <pre> * Conversion that occurs when a user opens an Android app for the first * time; Displayed in Google Ads UI as 'Android app install (first open)'. * </pre> * * <code>ANDROID_FIRST_OPEN = 12;</code> */ public static final int ANDROID_FIRST_OPEN_VALUE = 12; /** * <pre> * Call conversion that is uploaded through ConversionUploadService; * Displayed in Google Ads UI as 'Import from calls'. * </pre> * * <code>UPLOAD_CALLS = 13;</code> */ public static final int UPLOAD_CALLS_VALUE = 13; /** * <pre> * Conversion that comes from a linked Firebase event; * Displayed in Google Ads UI as 'Firebase'. * </pre> * * <code>FIREBASE = 14;</code> */ public static final int FIREBASE_VALUE = 14; /** * <pre> * Conversion that occurs when a user clicks on a mobile phone number; * Displayed in Google Ads UI as 'Phone number clicks'. * </pre> * * <code>CLICK_TO_CALL = 15;</code> */ public static final int CLICK_TO_CALL_VALUE = 15; /** * <pre> * Conversion that comes from Salesforce; * Displayed in Google Ads UI as 'Salesforce.com'. * </pre> * * <code>SALESFORCE = 16;</code> */ public static final int SALESFORCE_VALUE = 16; /** * <pre> * Conversion that comes from in-store purchases recorded by CRM; * Displayed in Google Ads UI as 'Store sales (data partner)'. * </pre> * * <code>STORE_SALES_CRM = 17;</code> */ public static final int STORE_SALES_CRM_VALUE = 17; /** * <pre> * Conversion that comes from in-store purchases from payment network; * Displayed in Google Ads UI as 'Store sales (payment network)'. * </pre> * * <code>STORE_SALES_PAYMENT_NETWORK = 18;</code> */ public static final int STORE_SALES_PAYMENT_NETWORK_VALUE = 18; /** * <pre> * Codeless Google Play conversion; * Displayed in Google Ads UI as 'Google Play'. * </pre> * * <code>GOOGLE_PLAY = 19;</code> */ public static final int GOOGLE_PLAY_VALUE = 19; /** * <pre> * Conversion that comes from a linked third-party app analytics event; * Displayed in Google Ads UI as 'Third-party app analytics'. * </pre> * * <code>THIRD_PARTY_APP_ANALYTICS = 20;</code> */ public static final int THIRD_PARTY_APP_ANALYTICS_VALUE = 20; /** * <pre> * Conversion that is controlled by Google Attribution. * </pre> * * <code>GOOGLE_ATTRIBUTION = 21;</code> */ public static final int GOOGLE_ATTRIBUTION_VALUE = 21; /** * <pre> * Store Sales conversion based on first-party or third-party merchant data * uploads. Displayed in Google Ads UI as 'Store sales (direct upload)'. * </pre> * * <code>STORE_SALES_DIRECT_UPLOAD = 23;</code> */ public static final int STORE_SALES_DIRECT_UPLOAD_VALUE = 23; /** * <pre> * Store Sales conversion based on first-party or third-party merchant * data uploads and/or from in-store purchases using cards from payment * networks. Displayed in Google Ads UI as 'Store sales'. * </pre> * * <code>STORE_SALES = 24;</code> */ public static final int STORE_SALES_VALUE = 24; /** * <pre> * Conversions imported from Search Ads 360 Floodlight data. * </pre> * * <code>SEARCH_ADS_360 = 25;</code> */ public static final int SEARCH_ADS_360_VALUE = 25; /** * <pre> * Conversions that track local actions from Google's products and services * after interacting with an ad. * </pre> * * <code>GOOGLE_HOSTED = 27;</code> */ public static final int GOOGLE_HOSTED_VALUE = 27; /** * <pre> * Conversions reported by Floodlight tags. * </pre> * * <code>FLOODLIGHT = 29;</code> */ public static final int FLOODLIGHT_VALUE = 29; /** * <pre> * Conversions that come from Google Analytics specifically for Search Ads * 360. Displayed in Google Ads UI as Analytics (SA360). * </pre> * * <code>ANALYTICS_SEARCH_ADS_360 = 31;</code> */ public static final int ANALYTICS_SEARCH_ADS_360_VALUE = 31; /** * <pre> * Conversion that comes from a linked Firebase event for Search Ads 360. * </pre> * * <code>FIREBASE_SEARCH_ADS_360 = 33;</code> */ public static final int FIREBASE_SEARCH_ADS_360_VALUE = 33; /** * <pre> * Conversion that is reported by Floodlight for DV360. * </pre> * * <code>DISPLAY_AND_VIDEO_360_FLOODLIGHT = 34;</code> */ public static final int DISPLAY_AND_VIDEO_360_FLOODLIGHT_VALUE = 34; 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 ExternalConversionSource 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 ExternalConversionSource forNumber(int value) { switch (value) { case 0: return UNSPECIFIED; case 1: return UNKNOWN; case 2: return WEBPAGE; case 3: return ANALYTICS; case 4: return UPLOAD; case 5: return AD_CALL_METRICS; case 6: return WEBSITE_CALL_METRICS; case 7: return STORE_VISITS; case 8: return ANDROID_IN_APP; case 9: return IOS_IN_APP; case 10: return IOS_FIRST_OPEN; case 11: return APP_UNSPECIFIED; case 12: return ANDROID_FIRST_OPEN; case 13: return UPLOAD_CALLS; case 14: return FIREBASE; case 15: return CLICK_TO_CALL; case 16: return SALESFORCE; case 17: return STORE_SALES_CRM; case 18: return STORE_SALES_PAYMENT_NETWORK; case 19: return GOOGLE_PLAY; case 20: return THIRD_PARTY_APP_ANALYTICS; case 21: return GOOGLE_ATTRIBUTION; case 23: return STORE_SALES_DIRECT_UPLOAD; case 24: return STORE_SALES; case 25: return SEARCH_ADS_360; case 27: return GOOGLE_HOSTED; case 29: return FLOODLIGHT; case 31: return ANALYTICS_SEARCH_ADS_360; case 33: return FIREBASE_SEARCH_ADS_360; case 34: return DISPLAY_AND_VIDEO_360_FLOODLIGHT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< ExternalConversionSource> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<ExternalConversionSource>() { public ExternalConversionSource findValueByNumber(int number) { return ExternalConversionSource.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.ads.googleads.v21.enums.ExternalConversionSourceEnum.getDescriptor().getEnumTypes().get(0); } private static final ExternalConversionSource[] VALUES = values(); public static ExternalConversionSource 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 ExternalConversionSource(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.ads.googleads.v21.enums.ExternalConversionSourceEnum.ExternalConversionSource) } 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 { getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; 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.enums.ExternalConversionSourceEnum)) { return super.equals(obj); } com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum other = (com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum) obj; 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 = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum 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.enums.ExternalConversionSourceEnum prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Container for enum describing the external conversion source that is * associated with a ConversionAction. * </pre> * * Protobuf type {@code google.ads.googleads.v21.enums.ExternalConversionSourceEnum} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.enums.ExternalConversionSourceEnum) com.google.ads.googleads.v21.enums.ExternalConversionSourceEnumOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v21_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v21_enums_ExternalConversionSourceEnum_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.class, com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.Builder.class); } // Construct using com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceProto.internal_static_google_ads_googleads_v21_enums_ExternalConversionSourceEnum_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum build() { com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum buildPartial() { com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum result = new com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum(this); onBuilt(); return result; } @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.enums.ExternalConversionSourceEnum) { return mergeFrom((com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum other) { if (other == com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum.getDefaultInstance()) return this; 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; 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; } @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.enums.ExternalConversionSourceEnum) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.enums.ExternalConversionSourceEnum) private static final com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum(); } public static com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExternalConversionSourceEnum> PARSER = new com.google.protobuf.AbstractParser<ExternalConversionSourceEnum>() { @java.lang.Override public ExternalConversionSourceEnum 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<ExternalConversionSourceEnum> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExternalConversionSourceEnum> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.enums.ExternalConversionSourceEnum getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/distributedlog
35,481
distributedlog-core/src/main/java/org/apache/distributedlog/ReadAheadEntryReader.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.distributedlog; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Stopwatch; import com.google.common.base.Ticker; import com.google.common.collect.Lists; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.apache.bookkeeper.stats.AlertStatsLogger; import org.apache.bookkeeper.versioning.Versioned; import org.apache.distributedlog.callback.LogSegmentListener; import org.apache.distributedlog.common.concurrent.FutureEventListener; import org.apache.distributedlog.common.concurrent.FutureUtils; import org.apache.distributedlog.exceptions.AlreadyTruncatedTransactionException; import org.apache.distributedlog.exceptions.DLIllegalStateException; import org.apache.distributedlog.exceptions.DLInterruptedException; import org.apache.distributedlog.exceptions.EndOfLogSegmentException; import org.apache.distributedlog.exceptions.LogNotFoundException; import org.apache.distributedlog.exceptions.UnexpectedException; import org.apache.distributedlog.io.AsyncCloseable; import org.apache.distributedlog.logsegment.LogSegmentEntryReader; import org.apache.distributedlog.logsegment.LogSegmentEntryStore; import org.apache.distributedlog.logsegment.LogSegmentFilter; import org.apache.distributedlog.util.OrderedScheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * New ReadAhead Reader that uses {@link org.apache.distributedlog.logsegment.LogSegmentEntryReader}. * * <p>NOTE: all the state changes happen in the same thread. All *unsafe* methods should be submitted to the order * scheduler using stream name as the key.</p> */ class ReadAheadEntryReader implements AsyncCloseable, LogSegmentListener, LogSegmentEntryReader.StateChangeListener, FutureEventListener<List<Entry.Reader>> { private static final Logger logger = LoggerFactory.getLogger(ReadAheadEntryReader.class); // // Static Functions // private static Function<LogSegmentEntryReader, Void> START_READER_FUNC = reader -> { reader.start(); return null; }; // // Internal Classes // class SegmentReader implements FutureEventListener<LogSegmentEntryReader> { private LogSegmentMetadata metadata; private final long startEntryId; private CompletableFuture<LogSegmentEntryReader> openFuture = null; private LogSegmentEntryReader reader = null; private boolean isStarted = false; private boolean isClosed = false; SegmentReader(LogSegmentMetadata metadata, long startEntryId) { this.metadata = metadata; this.startEntryId = startEntryId; } synchronized LogSegmentEntryReader getEntryReader() { return reader; } synchronized boolean isBeyondLastAddConfirmed() { return null != reader && reader.isBeyondLastAddConfirmed(); } synchronized LogSegmentMetadata getSegment() { return metadata; } synchronized boolean isReaderOpen() { return null != openFuture; } synchronized void openReader() { if (null != openFuture) { return; } openFuture = entryStore.openReader(metadata, startEntryId).whenComplete(this); } synchronized boolean isReaderStarted() { return isStarted; } synchronized void startRead() { if (isStarted) { return; } isStarted = true; if (null != reader) { reader.start(); } else { openFuture.thenApply(START_READER_FUNC); } } synchronized CompletableFuture<List<Entry.Reader>> readNext() { if (null != reader) { checkCatchingUpStatus(reader); return reader.readNext(numReadAheadEntries); } else { return openFuture.thenCompose(readFunc); } } synchronized void updateLogSegmentMetadata(final LogSegmentMetadata segment) { if (null != reader) { reader.onLogSegmentMetadataUpdated(segment); this.metadata = segment; } else { openFuture.thenAccept(reader1 -> { reader1.onLogSegmentMetadataUpdated(segment); synchronized (SegmentReader.this) { SegmentReader.this.metadata = segment; } }); } } @Override public synchronized void onSuccess(LogSegmentEntryReader reader) { this.reader = reader; if (reader.getSegment().isInProgress()) { reader.registerListener(ReadAheadEntryReader.this); } } @Override public void onFailure(Throwable cause) { // no-op, the failure will be propagated on first read. } synchronized boolean isClosed() { return isClosed; } synchronized CompletableFuture<Void> close() { if (null == openFuture) { return FutureUtils.Void(); } return FutureUtils.ensure( openFuture.thenCompose(reader1 -> reader1.asyncClose()), () -> { synchronized (SegmentReader.this) { isClosed = true; } }); } } private class ReadEntriesFunc implements Function<LogSegmentEntryReader, CompletableFuture<List<Entry.Reader>>> { private final int numEntries; ReadEntriesFunc(int numEntries) { this.numEntries = numEntries; } @Override public CompletableFuture<List<Entry.Reader>> apply(LogSegmentEntryReader reader) { checkCatchingUpStatus(reader); return reader.readNext(numEntries); } } private abstract class CloseableRunnable implements Runnable { @Override public void run() { synchronized (ReadAheadEntryReader.this) { if (null != closePromise) { return; } } try { safeRun(); } catch (Throwable cause) { logger.error("Caught unexpected exception : ", cause); } } abstract void safeRun(); } // // Functions // private final Function<LogSegmentEntryReader, CompletableFuture<List<Entry.Reader>>> readFunc; private final Runnable removeClosedSegmentReadersFunc = () -> removeClosedSegmentReaders(); // // Resources // private final DistributedLogConfiguration conf; private final BKLogReadHandler readHandler; private final LogSegmentEntryStore entryStore; private final OrderedScheduler scheduler; // // Parameters // private final String streamName; private final DLSN fromDLSN; private final int maxCachedEntries; private final int numReadAheadEntries; private final int idleWarnThresholdMillis; // // Cache // private final LinkedBlockingQueue<Entry.Reader> entryQueue; // // State of the reader // private final AtomicBoolean started = new AtomicBoolean(false); private boolean isInitialized = false; private boolean readAheadPaused = false; private CompletableFuture<Void> closePromise = null; // segment readers private long currentSegmentSequenceNumber; private SegmentReader currentSegmentReader; private SegmentReader nextSegmentReader; private DLSN lastDLSN; private final EntryPosition nextEntryPosition; private volatile boolean isCatchingUp = true; private final LinkedList<SegmentReader> segmentReaders; private final LinkedList<SegmentReader> segmentReadersToClose; // last exception that this reader encounters private final AtomicReference<IOException> lastException = new AtomicReference<IOException>(null); // last entry added time private final Stopwatch lastEntryAddedTime; // state change notification private final CopyOnWriteArraySet<AsyncNotification> stateChangeNotifications = new CopyOnWriteArraySet<AsyncNotification>(); // idle reader check task private final ScheduledFuture<?> idleReaderCheckTask; // // Stats // private final AlertStatsLogger alertStatsLogger; public ReadAheadEntryReader(String streamName, DLSN fromDLSN, DistributedLogConfiguration conf, BKLogReadHandler readHandler, LogSegmentEntryStore entryStore, OrderedScheduler scheduler, Ticker ticker, AlertStatsLogger alertStatsLogger) { this.streamName = streamName; this.fromDLSN = lastDLSN = fromDLSN; this.nextEntryPosition = new EntryPosition( fromDLSN.getLogSegmentSequenceNo(), fromDLSN.getEntryId()); this.conf = conf; this.maxCachedEntries = conf.getReadAheadMaxRecords(); this.numReadAheadEntries = conf.getReadAheadBatchSize(); this.idleWarnThresholdMillis = conf.getReaderIdleWarnThresholdMillis(); this.readHandler = readHandler; this.entryStore = entryStore; this.scheduler = scheduler; this.readFunc = new ReadEntriesFunc(numReadAheadEntries); this.alertStatsLogger = alertStatsLogger; // create the segment reader list this.segmentReaders = new LinkedList<SegmentReader>(); this.segmentReadersToClose = new LinkedList<SegmentReader>(); // create the readahead entry queue this.entryQueue = new LinkedBlockingQueue<Entry.Reader>(); // start the idle reader detection lastEntryAddedTime = Stopwatch.createStarted(ticker); // start the idle reader check task idleReaderCheckTask = scheduleIdleReaderTaskIfNecessary(); } private ScheduledFuture<?> scheduleIdleReaderTaskIfNecessary() { if (idleWarnThresholdMillis < Integer.MAX_VALUE && idleWarnThresholdMillis > 0) { return scheduler.scheduleAtFixedRate(streamName, () -> { if (!isReaderIdle(idleWarnThresholdMillis, TimeUnit.MILLISECONDS)) { return; } // the readahead has been idle unsafeCheckIfReadAheadIsIdle(); }, idleWarnThresholdMillis, idleWarnThresholdMillis, TimeUnit.MILLISECONDS); } return null; } private void unsafeCheckIfReadAheadIsIdle() { boolean forceReadLogSegments = (null == currentSegmentReader) || currentSegmentReader.isBeyondLastAddConfirmed(); if (forceReadLogSegments) { readHandler.readLogSegmentsFromStore( LogSegmentMetadata.COMPARATOR, LogSegmentFilter.DEFAULT_FILTER, null ).whenComplete(new FutureEventListener<Versioned<List<LogSegmentMetadata>>>() { @Override public void onFailure(Throwable cause) { // do nothing here since it would be retried on next idle reader check task } @Override public void onSuccess(Versioned<List<LogSegmentMetadata>> segments) { onSegmentsUpdated(segments.getValue()); } }); } } private void cancelIdleReaderTask() { if (null != idleReaderCheckTask) { idleReaderCheckTask.cancel(true); } } @VisibleForTesting EntryPosition getNextEntryPosition() { return nextEntryPosition; } @VisibleForTesting SegmentReader getCurrentSegmentReader() { return currentSegmentReader; } @VisibleForTesting long getCurrentSegmentSequenceNumber() { return currentSegmentSequenceNumber; } @VisibleForTesting SegmentReader getNextSegmentReader() { return nextSegmentReader; } @VisibleForTesting LinkedList<SegmentReader> getSegmentReaders() { return segmentReaders; } @VisibleForTesting boolean isInitialized() { return isInitialized; } private void orderedSubmit(Runnable runnable) { synchronized (this) { if (null != closePromise) { return; } } try { scheduler.submit(streamName, runnable); } catch (RejectedExecutionException ree) { logger.debug("Failed to submit and execute an operation for readhead entry reader of {}", streamName, ree); } } public void start(final List<LogSegmentMetadata> segmentList) { logger.info("Starting the readahead entry reader for {} : segments = {}", readHandler.getFullyQualifiedName(), segmentList); started.set(true); processLogSegments(segmentList); } private void removeClosedSegmentReaders() { orderedSubmit(new CloseableRunnable() { @Override void safeRun() { unsafeRemoveClosedSegmentReaders(); } }); } private void unsafeRemoveClosedSegmentReaders() { SegmentReader reader = segmentReadersToClose.peekFirst(); while (null != reader) { if (reader.isClosed()) { segmentReadersToClose.pollFirst(); reader = segmentReadersToClose.peekFirst(); } else { break; } } } synchronized boolean isClosed() { return null != closePromise; } @Override public CompletableFuture<Void> asyncClose() { final CompletableFuture<Void> closeFuture; synchronized (this) { if (null != closePromise) { return closePromise; } closePromise = closeFuture = new CompletableFuture<Void>(); } // cancel the idle reader task cancelIdleReaderTask(); // use runnable here instead of CloseableRunnable, // because we need this to be executed try { scheduler.submit(streamName, new Runnable() { @Override public void run() { unsafeAsyncClose(closeFuture); } }); } catch (RejectedExecutionException ree) { logger.warn("Scheduler has been shutdown before closing the readahead entry reader for stream {}", streamName, ree); unsafeAsyncClose(closeFuture); } return closeFuture; } private void unsafeAsyncClose(CompletableFuture<Void> closePromise) { List<CompletableFuture<Void>> closeFutures = Lists.newArrayListWithExpectedSize( segmentReaders.size() + segmentReadersToClose.size() + 1); if (null != currentSegmentReader) { segmentReadersToClose.add(currentSegmentReader); } if (null != nextSegmentReader) { segmentReadersToClose.add(nextSegmentReader); } for (SegmentReader reader : segmentReaders) { segmentReadersToClose.add(reader); } segmentReaders.clear(); for (SegmentReader reader : segmentReadersToClose) { closeFutures.add(reader.close()); } FutureUtils.proxyTo( FutureUtils.collect(closeFutures).thenApply((value) -> null), closePromise); } // // Reader State Changes // ReadAheadEntryReader addStateChangeNotification(AsyncNotification notification) { this.stateChangeNotifications.add(notification); return this; } ReadAheadEntryReader removeStateChangeNotification(AsyncNotification notification) { this.stateChangeNotifications.remove(notification); return this; } private void notifyStateChangeOnSuccess() { for (AsyncNotification notification : stateChangeNotifications) { notification.notifyOnOperationComplete(); } } private void notifyStateChangeOnFailure(Throwable cause) { for (AsyncNotification notification : stateChangeNotifications) { notification.notifyOnError(cause); } } void setLastException(IOException cause) { if (!lastException.compareAndSet(null, cause)) { logger.debug("last exception has already been set to ", lastException.get()); } // the exception is set and notify the state change notifyStateChangeOnFailure(cause); } void checkLastException() throws IOException { if (null != lastException.get()) { throw lastException.get(); } } void checkCatchingUpStatus(LogSegmentEntryReader reader) { if (reader.getSegment().isInProgress() && isCatchingUp && reader.hasCaughtUpOnInprogress()) { logger.info("ReadAhead for {} is caught up at entry {} @ log segment {}.", new Object[] { readHandler.getFullyQualifiedName(), reader.getLastAddConfirmed(), reader.getSegment() }); isCatchingUp = false; } } void markCaughtup() { if (isCatchingUp) { isCatchingUp = false; logger.info("ReadAhead for {} is caught up", readHandler.getFullyQualifiedName()); } } public boolean isReadAheadCaughtUp() { return !isCatchingUp; } @Override public void onCaughtupOnInprogress() { markCaughtup(); } // // ReadAhead State Machine // @Override public void onSuccess(List<Entry.Reader> entries) { if (isClosed()) { // if readahead is closing, don't put the entries to the queue for (Entry.Reader entry : entries) { entry.release(); } return; } lastEntryAddedTime.reset().start(); for (Entry.Reader entry : entries) { entryQueue.add(entry); } if (!entries.isEmpty()) { Entry.Reader lastEntry = entries.get(entries.size() - 1); nextEntryPosition.advance(lastEntry.getLSSN(), lastEntry.getEntryId() + 1); } // notify on data available notifyStateChangeOnSuccess(); if (entryQueue.size() >= maxCachedEntries) { pauseReadAheadOnCacheFull(); } else { scheduleReadNext(); } } @Override public void onFailure(Throwable cause) { if (cause instanceof EndOfLogSegmentException) { // we reach end of the log segment moveToNextLogSegment(); return; } if (cause instanceof IOException) { setLastException((IOException) cause); } else { setLastException(new UnexpectedException("Unexpected non I/O exception", cause)); } } private synchronized void invokeReadAhead() { if (readAheadPaused) { scheduleReadNext(); readAheadPaused = false; } } private synchronized void pauseReadAheadOnCacheFull() { this.readAheadPaused = true; if (!isCacheFull()) { invokeReadAhead(); } } private synchronized void pauseReadAheadOnNoMoreLogSegments() { this.readAheadPaused = true; } // // Cache Related Methods // public Entry.Reader getNextReadAheadEntry(long waitTime, TimeUnit waitTimeUnit) throws IOException { if (null != lastException.get()) { throw lastException.get(); } Entry.Reader entry; try { entry = entryQueue.poll(waitTime, waitTimeUnit); } catch (InterruptedException e) { throw new DLInterruptedException("Interrupted on waiting next readahead entry : ", e); } try { return entry; } finally { // resume readahead if the cache becomes empty if (null != entry && !isCacheFull()) { invokeReadAhead(); } } } /** * Return number cached entries. * * @return number cached entries. */ public int getNumCachedEntries() { return entryQueue.size(); } /** * Return if the cache is full. * * @return true if the cache is full, otherwise false. */ public boolean isCacheFull() { return getNumCachedEntries() >= maxCachedEntries; } @VisibleForTesting public boolean isCacheEmpty() { return entryQueue.isEmpty(); } /** * Check whether the readahead becomes stall. * * @param idleReaderErrorThreshold idle reader error threshold * @param timeUnit time unit of the idle reader error threshold * @return true if the readahead becomes stall, otherwise false. */ public boolean isReaderIdle(int idleReaderErrorThreshold, TimeUnit timeUnit) { return (lastEntryAddedTime.elapsed(timeUnit) > idleReaderErrorThreshold); } // // LogSegment Management // void processLogSegments(final List<LogSegmentMetadata> segments) { orderedSubmit(new CloseableRunnable() { @Override void safeRun() { unsafeProcessLogSegments(segments); } }); } private void unsafeProcessLogSegments(List<LogSegmentMetadata> segments) { if (isInitialized) { unsafeReinitializeLogSegments(segments); } else { unsafeInitializeLogSegments(segments); } } /** * Update the log segment metadata. * * @param reader the reader to update the metadata * @param newMetadata the new metadata received * @return true if successfully, false on encountering errors */ private boolean updateLogSegmentMetadata(SegmentReader reader, LogSegmentMetadata newMetadata) { if (reader.getSegment().getLogSegmentSequenceNumber() != newMetadata.getLogSegmentSequenceNumber()) { logger.error("Inconsistent state found in entry reader for {} : " + "current segment = {}, new segment = {}", new Object[] { streamName, reader.getSegment(), newMetadata }); setLastException(new DLIllegalStateException("Inconsistent state found in entry reader for " + streamName + " : current segment = " + reader.getSegment() + ", new segment = " + newMetadata)); return false; } if (!reader.getSegment().isInProgress() && newMetadata.isInProgress()) { setLastException(new DLIllegalStateException("An inprogress log segment " + newMetadata + " received after a closed log segment " + reader.getSegment() + " on reading segment " + newMetadata.getLogSegmentSequenceNumber() + " @ stream " + streamName)); return false; } if (reader.getSegment().isInProgress() && !newMetadata.isInProgress()) { reader.updateLogSegmentMetadata(newMetadata); } return true; } /** * Reinitialize the log segments. */ private void unsafeReinitializeLogSegments(List<LogSegmentMetadata> segments) { logger.info("Reinitialize log segments with {}", segments); int segmentIdx = 0; for (; segmentIdx < segments.size(); segmentIdx++) { LogSegmentMetadata segment = segments.get(segmentIdx); if (segment.getLogSegmentSequenceNumber() < currentSegmentSequenceNumber) { continue; } break; } if (segmentIdx >= segments.size()) { return; } LogSegmentMetadata segment = segments.get(segmentIdx); if (null != currentSegmentReader) { if (!updateLogSegmentMetadata(currentSegmentReader, segment)) { return; } } else { if (currentSegmentSequenceNumber != segment.getLogSegmentSequenceNumber()) { logger.error("Inconsistent state found in entry reader for {} : " + "current segment sn = {}, new segment sn = {}", new Object[] { streamName, currentSegmentSequenceNumber, segment.getLogSegmentSequenceNumber() }); setLastException(new DLIllegalStateException("Inconsistent state found in entry reader for " + streamName + " : current segment sn = " + currentSegmentSequenceNumber + ", new segment sn = " + segment.getLogSegmentSequenceNumber())); return; } } segmentIdx++; if (segmentIdx >= segments.size()) { return; } // check next segment segment = segments.get(segmentIdx); if (null != nextSegmentReader) { if (!updateLogSegmentMetadata(nextSegmentReader, segment)) { return; } segmentIdx++; } // check the segment readers in the queue for (int readerIdx = 0; readerIdx < segmentReaders.size() && segmentIdx < segments.size(); readerIdx++, segmentIdx++) { SegmentReader reader = segmentReaders.get(readerIdx); segment = segments.get(segmentIdx); if (!updateLogSegmentMetadata(reader, segment)) { return; } } // add the remaining segments to the reader queue for (; segmentIdx < segments.size(); segmentIdx++) { segment = segments.get(segmentIdx); SegmentReader reader = new SegmentReader(segment, 0L); reader.openReader(); segmentReaders.add(reader); } if (null == currentSegmentReader) { unsafeMoveToNextLogSegment(); } // resume readahead if necessary invokeReadAhead(); } /** * Initialize the reader with the log <i>segments</i>. * * @param segments list of log segments */ private void unsafeInitializeLogSegments(List<LogSegmentMetadata> segments) { if (segments.isEmpty()) { // not initialize the background reader, until the first log segment is notified return; } boolean skipTruncatedLogSegments = true; DLSN dlsnToStart = fromDLSN; // positioning the reader for (int i = 0; i < segments.size(); i++) { LogSegmentMetadata segment = segments.get(i); // skip any log segments that have smaller log segment sequence numbers if (segment.getLogSegmentSequenceNumber() < fromDLSN.getLogSegmentSequenceNo()) { continue; } // if the log segment is truncated, skip it. if (skipTruncatedLogSegments && !conf.getIgnoreTruncationStatus() && segment.isTruncated()) { continue; } // if the log segment is partially truncated, move the start dlsn to the min active dlsn if (skipTruncatedLogSegments && !conf.getIgnoreTruncationStatus() && segment.isPartiallyTruncated()) { if (segment.getMinActiveDLSN().compareTo(fromDLSN) > 0) { dlsnToStart = segment.getMinActiveDLSN(); } } skipTruncatedLogSegments = false; if (!isAllowedToPosition(segment, dlsnToStart)) { logger.error("segment {} is not allowed to position at {}", segment, dlsnToStart); return; } SegmentReader reader = new SegmentReader(segment, segment.getLogSegmentSequenceNumber() == dlsnToStart.getLogSegmentSequenceNo() ? dlsnToStart.getEntryId() : 0L); segmentReaders.add(reader); } if (segmentReaders.isEmpty()) { // not initialize the background reader, until the first log segment is available to read return; } currentSegmentReader = segmentReaders.pollFirst(); currentSegmentReader.openReader(); currentSegmentReader.startRead(); currentSegmentSequenceNumber = currentSegmentReader.getSegment().getLogSegmentSequenceNumber(); unsafeReadNext(currentSegmentReader); if (!segmentReaders.isEmpty()) { for (SegmentReader reader : segmentReaders) { reader.openReader(); } unsafePrefetchNextSegment(true); } // mark the reader initialized isInitialized = true; } private void unsafePrefetchNextSegment(boolean onlyInprogressLogSegment) { SegmentReader nextReader = segmentReaders.peekFirst(); // open the next log segment if it is inprogress if (null != nextReader) { if (onlyInprogressLogSegment && !nextReader.getSegment().isInProgress()) { return; } nextReader.startRead(); nextSegmentReader = nextReader; segmentReaders.pollFirst(); } } /** * Check if we are allowed to position the reader at <i>fromDLSN</i>. * * @return true if it is allowed, otherwise false. */ private boolean isAllowedToPosition(LogSegmentMetadata segment, DLSN fromDLSN) { if (segment.isTruncated() && segment.getLastDLSN().compareTo(fromDLSN) >= 0 && !conf.getIgnoreTruncationStatus()) { setLastException(new AlreadyTruncatedTransactionException(streamName + " : trying to position read ahead at " + fromDLSN + " on a segment " + segment + " that is already marked as truncated")); return false; } if (segment.isPartiallyTruncated() && segment.getMinActiveDLSN().compareTo(fromDLSN) > 0) { if (conf.getAlertWhenPositioningOnTruncated()) { alertStatsLogger.raise("Trying to position reader on {} when {} is marked partially truncated", fromDLSN, segment); } if (!conf.getIgnoreTruncationStatus()) { logger.error("{}: Trying to position reader on {} when {} is marked partially truncated", new Object[]{ streamName, fromDLSN, segment }); setLastException(new AlreadyTruncatedTransactionException(streamName + " : trying to position read ahead at " + fromDLSN + " on a segment " + segment + " that is already marked as truncated")); return false; } } return true; } void moveToNextLogSegment() { orderedSubmit(new CloseableRunnable() { @Override void safeRun() { unsafeMoveToNextLogSegment(); } }); } private void unsafeMoveToNextLogSegment() { if (null != currentSegmentReader) { segmentReadersToClose.add(currentSegmentReader); FutureUtils.ensure( currentSegmentReader.close(), removeClosedSegmentReadersFunc); logger.debug("close current segment reader {}", currentSegmentReader.getSegment()); currentSegmentReader = null; } boolean hasSegmentToRead = false; if (null != nextSegmentReader) { currentSegmentReader = nextSegmentReader; logger.debug("move to read segment {}", currentSegmentReader.getSegment()); currentSegmentSequenceNumber = currentSegmentReader.getSegment().getLogSegmentSequenceNumber(); nextSegmentReader = null; // start reading unsafeReadNext(currentSegmentReader); unsafePrefetchNextSegment(true); hasSegmentToRead = true; } else { unsafePrefetchNextSegment(false); if (null != nextSegmentReader) { currentSegmentReader = nextSegmentReader; logger.debug("move to read segment {}", currentSegmentReader.getSegment()); currentSegmentSequenceNumber = currentSegmentReader.getSegment().getLogSegmentSequenceNumber(); nextSegmentReader = null; unsafeReadNext(currentSegmentReader); unsafePrefetchNextSegment(true); hasSegmentToRead = true; } } if (!hasSegmentToRead) { // no more segment to read, wait until new log segment arrive if (isCatchingUp) { logger.info("ReadAhead for {} is caught up and no log segments to read now", readHandler.getFullyQualifiedName()); isCatchingUp = false; } pauseReadAheadOnNoMoreLogSegments(); } } void scheduleReadNext() { orderedSubmit(new CloseableRunnable() { @Override void safeRun() { if (null == currentSegmentReader) { pauseReadAheadOnNoMoreLogSegments(); return; } unsafeReadNext(currentSegmentReader); } }); } private void unsafeReadNext(SegmentReader reader) { reader.readNext().whenComplete(this); } @Override public void onSegmentsUpdated(List<LogSegmentMetadata> segments) { if (!started.get()) { return; } logger.info("segments is updated with {}", segments); processLogSegments(segments); } @Override public void onLogStreamDeleted() { setLastException(new LogNotFoundException("Log stream " + streamName + " is deleted")); } }
googleapis/google-cloud-java
35,478
java-vertexai/proto-google-cloud-vertexai-v1/src/main/java/com/google/cloud/vertexai/api/PredictRequestResponseLoggingConfig.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vertexai/v1/endpoint.proto // Protobuf Java Version: 3.25.3 package com.google.cloud.vertexai.api; /** * * * <pre> * Configuration for logging request-response to a BigQuery table. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig} */ public final class PredictRequestResponseLoggingConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig) PredictRequestResponseLoggingConfigOrBuilder { private static final long serialVersionUID = 0L; // Use PredictRequestResponseLoggingConfig.newBuilder() to construct. private PredictRequestResponseLoggingConfig( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PredictRequestResponseLoggingConfig() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new PredictRequestResponseLoggingConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.EndpointProto .internal_static_google_cloud_vertexai_v1_PredictRequestResponseLoggingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.EndpointProto .internal_static_google_cloud_vertexai_v1_PredictRequestResponseLoggingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.class, com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.Builder.class); } private int bitField0_; public static final int ENABLED_FIELD_NUMBER = 1; private boolean enabled_ = false; /** * * * <pre> * If logging is enabled or not. * </pre> * * <code>bool enabled = 1;</code> * * @return The enabled. */ @java.lang.Override public boolean getEnabled() { return enabled_; } public static final int SAMPLING_RATE_FIELD_NUMBER = 2; private double samplingRate_ = 0D; /** * * * <pre> * Percentage of requests to be logged, expressed as a fraction in * range(0,1]. * </pre> * * <code>double sampling_rate = 2;</code> * * @return The samplingRate. */ @java.lang.Override public double getSamplingRate() { return samplingRate_; } public static final int BIGQUERY_DESTINATION_FIELD_NUMBER = 3; private com.google.cloud.vertexai.api.BigQueryDestination bigqueryDestination_; /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> * * @return Whether the bigqueryDestination field is set. */ @java.lang.Override public boolean hasBigqueryDestination() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> * * @return The bigqueryDestination. */ @java.lang.Override public com.google.cloud.vertexai.api.BigQueryDestination getBigqueryDestination() { return bigqueryDestination_ == null ? com.google.cloud.vertexai.api.BigQueryDestination.getDefaultInstance() : bigqueryDestination_; } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ @java.lang.Override public com.google.cloud.vertexai.api.BigQueryDestinationOrBuilder getBigqueryDestinationOrBuilder() { return bigqueryDestination_ == null ? com.google.cloud.vertexai.api.BigQueryDestination.getDefaultInstance() : bigqueryDestination_; } 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 (enabled_ != false) { output.writeBool(1, enabled_); } if (java.lang.Double.doubleToRawLongBits(samplingRate_) != 0) { output.writeDouble(2, samplingRate_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getBigqueryDestination()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (enabled_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, enabled_); } if (java.lang.Double.doubleToRawLongBits(samplingRate_) != 0) { size += com.google.protobuf.CodedOutputStream.computeDoubleSize(2, samplingRate_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getBigqueryDestination()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig)) { return super.equals(obj); } com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig other = (com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig) obj; if (getEnabled() != other.getEnabled()) return false; if (java.lang.Double.doubleToLongBits(getSamplingRate()) != java.lang.Double.doubleToLongBits(other.getSamplingRate())) return false; if (hasBigqueryDestination() != other.hasBigqueryDestination()) return false; if (hasBigqueryDestination()) { if (!getBigqueryDestination().equals(other.getBigqueryDestination())) 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) + ENABLED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getEnabled()); hash = (37 * hash) + SAMPLING_RATE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getSamplingRate())); if (hasBigqueryDestination()) { hash = (37 * hash) + BIGQUERY_DESTINATION_FIELD_NUMBER; hash = (53 * hash) + getBigqueryDestination().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Configuration for logging request-response to a BigQuery table. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig) com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.EndpointProto .internal_static_google_cloud_vertexai_v1_PredictRequestResponseLoggingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.EndpointProto .internal_static_google_cloud_vertexai_v1_PredictRequestResponseLoggingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.class, com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.Builder.class); } // Construct using // com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBigqueryDestinationFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; enabled_ = false; samplingRate_ = 0D; bigqueryDestination_ = null; if (bigqueryDestinationBuilder_ != null) { bigqueryDestinationBuilder_.dispose(); bigqueryDestinationBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vertexai.api.EndpointProto .internal_static_google_cloud_vertexai_v1_PredictRequestResponseLoggingConfig_descriptor; } @java.lang.Override public com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig getDefaultInstanceForType() { return com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig build() { com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig buildPartial() { com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig result = new com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.enabled_ = enabled_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.samplingRate_ = samplingRate_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.bigqueryDestination_ = bigqueryDestinationBuilder_ == null ? bigqueryDestination_ : bigqueryDestinationBuilder_.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.vertexai.api.PredictRequestResponseLoggingConfig) { return mergeFrom((com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig other) { if (other == com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig.getDefaultInstance()) return this; if (other.getEnabled() != false) { setEnabled(other.getEnabled()); } if (other.getSamplingRate() != 0D) { setSamplingRate(other.getSamplingRate()); } if (other.hasBigqueryDestination()) { mergeBigqueryDestination(other.getBigqueryDestination()); } 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: { enabled_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 case 17: { samplingRate_ = input.readDouble(); bitField0_ |= 0x00000002; break; } // case 17 case 26: { input.readMessage( getBigqueryDestinationFieldBuilder().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 boolean enabled_; /** * * * <pre> * If logging is enabled or not. * </pre> * * <code>bool enabled = 1;</code> * * @return The enabled. */ @java.lang.Override public boolean getEnabled() { return enabled_; } /** * * * <pre> * If logging is enabled or not. * </pre> * * <code>bool enabled = 1;</code> * * @param value The enabled to set. * @return This builder for chaining. */ public Builder setEnabled(boolean value) { enabled_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * If logging is enabled or not. * </pre> * * <code>bool enabled = 1;</code> * * @return This builder for chaining. */ public Builder clearEnabled() { bitField0_ = (bitField0_ & ~0x00000001); enabled_ = false; onChanged(); return this; } private double samplingRate_; /** * * * <pre> * Percentage of requests to be logged, expressed as a fraction in * range(0,1]. * </pre> * * <code>double sampling_rate = 2;</code> * * @return The samplingRate. */ @java.lang.Override public double getSamplingRate() { return samplingRate_; } /** * * * <pre> * Percentage of requests to be logged, expressed as a fraction in * range(0,1]. * </pre> * * <code>double sampling_rate = 2;</code> * * @param value The samplingRate to set. * @return This builder for chaining. */ public Builder setSamplingRate(double value) { samplingRate_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Percentage of requests to be logged, expressed as a fraction in * range(0,1]. * </pre> * * <code>double sampling_rate = 2;</code> * * @return This builder for chaining. */ public Builder clearSamplingRate() { bitField0_ = (bitField0_ & ~0x00000002); samplingRate_ = 0D; onChanged(); return this; } private com.google.cloud.vertexai.api.BigQueryDestination bigqueryDestination_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vertexai.api.BigQueryDestination, com.google.cloud.vertexai.api.BigQueryDestination.Builder, com.google.cloud.vertexai.api.BigQueryDestinationOrBuilder> bigqueryDestinationBuilder_; /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> * * @return Whether the bigqueryDestination field is set. */ public boolean hasBigqueryDestination() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> * * @return The bigqueryDestination. */ public com.google.cloud.vertexai.api.BigQueryDestination getBigqueryDestination() { if (bigqueryDestinationBuilder_ == null) { return bigqueryDestination_ == null ? com.google.cloud.vertexai.api.BigQueryDestination.getDefaultInstance() : bigqueryDestination_; } else { return bigqueryDestinationBuilder_.getMessage(); } } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public Builder setBigqueryDestination(com.google.cloud.vertexai.api.BigQueryDestination value) { if (bigqueryDestinationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } bigqueryDestination_ = value; } else { bigqueryDestinationBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public Builder setBigqueryDestination( com.google.cloud.vertexai.api.BigQueryDestination.Builder builderForValue) { if (bigqueryDestinationBuilder_ == null) { bigqueryDestination_ = builderForValue.build(); } else { bigqueryDestinationBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public Builder mergeBigqueryDestination( com.google.cloud.vertexai.api.BigQueryDestination value) { if (bigqueryDestinationBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && bigqueryDestination_ != null && bigqueryDestination_ != com.google.cloud.vertexai.api.BigQueryDestination.getDefaultInstance()) { getBigqueryDestinationBuilder().mergeFrom(value); } else { bigqueryDestination_ = value; } } else { bigqueryDestinationBuilder_.mergeFrom(value); } if (bigqueryDestination_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public Builder clearBigqueryDestination() { bitField0_ = (bitField0_ & ~0x00000004); bigqueryDestination_ = null; if (bigqueryDestinationBuilder_ != null) { bigqueryDestinationBuilder_.dispose(); bigqueryDestinationBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public com.google.cloud.vertexai.api.BigQueryDestination.Builder getBigqueryDestinationBuilder() { bitField0_ |= 0x00000004; onChanged(); return getBigqueryDestinationFieldBuilder().getBuilder(); } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ public com.google.cloud.vertexai.api.BigQueryDestinationOrBuilder getBigqueryDestinationOrBuilder() { if (bigqueryDestinationBuilder_ != null) { return bigqueryDestinationBuilder_.getMessageOrBuilder(); } else { return bigqueryDestination_ == null ? com.google.cloud.vertexai.api.BigQueryDestination.getDefaultInstance() : bigqueryDestination_; } } /** * * * <pre> * BigQuery table for logging. * If only given a project, a new dataset will be created with name * `logging_&lt;endpoint-display-name&gt;_&lt;endpoint-id&gt;` where * &lt;endpoint-display-name&gt; will be made BigQuery-dataset-name compatible (e.g. * most special characters will become underscores). If no table name is * given, a new table will be created with name `request_response_logging` * </pre> * * <code>.google.cloud.vertexai.v1.BigQueryDestination bigquery_destination = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vertexai.api.BigQueryDestination, com.google.cloud.vertexai.api.BigQueryDestination.Builder, com.google.cloud.vertexai.api.BigQueryDestinationOrBuilder> getBigqueryDestinationFieldBuilder() { if (bigqueryDestinationBuilder_ == null) { bigqueryDestinationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.vertexai.api.BigQueryDestination, com.google.cloud.vertexai.api.BigQueryDestination.Builder, com.google.cloud.vertexai.api.BigQueryDestinationOrBuilder>( getBigqueryDestination(), getParentForChildren(), isClean()); bigqueryDestination_ = null; } return bigqueryDestinationBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig) } // @@protoc_insertion_point(class_scope:google.cloud.vertexai.v1.PredictRequestResponseLoggingConfig) private static final com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig(); } public static com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PredictRequestResponseLoggingConfig> PARSER = new com.google.protobuf.AbstractParser<PredictRequestResponseLoggingConfig>() { @java.lang.Override public PredictRequestResponseLoggingConfig 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<PredictRequestResponseLoggingConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PredictRequestResponseLoggingConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vertexai.api.PredictRequestResponseLoggingConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/pulsar
35,534
pulsar-functions/utils/src/test/java/org/apache/pulsar/functions/utils/FunctionConfigUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.functions.utils; import static org.apache.pulsar.common.functions.FunctionConfig.ProcessingGuarantees.EFFECTIVELY_ONCE; import static org.apache.pulsar.common.functions.FunctionConfig.Runtime.PYTHON; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; import com.google.gson.Gson; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.api.CompressionType; import org.apache.pulsar.client.api.ConsumerCryptoFailureAction; import org.apache.pulsar.client.api.ProducerCryptoFailureAction; import org.apache.pulsar.client.api.SubscriptionInitialPosition; import org.apache.pulsar.client.impl.schema.JSONSchema; import org.apache.pulsar.common.functions.ConsumerConfig; import org.apache.pulsar.common.functions.CryptoConfig; import org.apache.pulsar.common.functions.FunctionConfig; import org.apache.pulsar.common.functions.ProducerConfig; import org.apache.pulsar.common.functions.Resources; import org.apache.pulsar.common.functions.WindowConfig; import org.apache.pulsar.common.util.Reflections; import org.apache.pulsar.functions.api.Record; import org.apache.pulsar.functions.api.WindowContext; import org.apache.pulsar.functions.api.WindowFunction; import org.apache.pulsar.functions.api.utils.IdentityFunction; import org.apache.pulsar.functions.proto.Function; import org.apache.pulsar.functions.proto.Function.FunctionDetails; import org.json.JSONException; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.testng.annotations.Test; /** * Unit test of {@link Reflections}. */ @Slf4j public class FunctionConfigUtilsTest { public static class WordCountWindowFunction implements WindowFunction<String, Void> { @Override public Void process(Collection<Record<String>> inputs, WindowContext context) throws Exception { for (Record<String> input : inputs) { Arrays.asList(input.getValue().split("\\.")).forEach(word -> context.incrCounter(word, 1)); } return null; } } @Test public void testAutoAckConvertFailed() { FunctionConfig functionConfig = new FunctionConfig(); functionConfig.setAutoAck(false); functionConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATMOST_ONCE); assertThrows(IllegalArgumentException.class, () -> { FunctionConfigUtils.convert(functionConfig); }); } @Test public void testConvertBackFidelity() throws JSONException { FunctionConfig functionConfig = new FunctionConfig(); functionConfig.setTenant("test-tenant"); functionConfig.setNamespace("test-namespace"); functionConfig.setName("test-function"); functionConfig.setParallelism(1); functionConfig.setClassName(IdentityFunction.class.getName()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder() .isRegexPattern(true) .serdeClassName("test-serde") .poolMessages(true).build()); functionConfig.setInputSpecs(inputSpecs); functionConfig.setOutput("test-output"); functionConfig.setOutputSerdeClassName("test-serde"); functionConfig.setRuntime(FunctionConfig.Runtime.JAVA); functionConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE); functionConfig.setRetainOrdering(false); functionConfig.setRetainKeyOrdering(false); functionConfig.setForwardSourceMessageProperty(true); functionConfig.setUserConfig(new HashMap<>()); functionConfig.setAutoAck(true); functionConfig.setTimeoutMs(2000L); functionConfig.setRuntimeFlags("-DKerberos"); ProducerConfig producerConfig = new ProducerConfig(); producerConfig.setMaxPendingMessages(100); producerConfig.setMaxPendingMessagesAcrossPartitions(1000); producerConfig.setUseThreadLocalProducers(true); producerConfig.setBatchBuilder("DEFAULT"); producerConfig.setCompressionType(CompressionType.ZLIB); functionConfig.setProducerConfig(producerConfig); Function.FunctionDetails functionDetails = FunctionConfigUtils.convert(functionConfig); FunctionConfig convertedConfig = FunctionConfigUtils.convertFromDetails(functionDetails); // add default resources functionConfig.setResources(Resources.getDefaultResources()); // set default cleanupSubscription config functionConfig.setCleanupSubscription(true); JSONAssert.assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(convertedConfig), JSONCompareMode.STRICT ); } @Test public void testConvertWindow() { FunctionConfig functionConfig = new FunctionConfig(); functionConfig.setTenant("test-tenant"); functionConfig.setNamespace("test-namespace"); functionConfig.setName("test-function"); functionConfig.setParallelism(1); functionConfig.setClassName(WordCountWindowFunction.class.getName()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true) .serdeClassName("test-serde").build()); functionConfig.setInputSpecs(inputSpecs); functionConfig.setOutput("test-output"); functionConfig.setOutputSerdeClassName("test-serde"); functionConfig.setRuntime(FunctionConfig.Runtime.JAVA); functionConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE); functionConfig.setRetainOrdering(false); functionConfig.setRetainKeyOrdering(false); functionConfig.setForwardSourceMessageProperty(true); functionConfig.setUserConfig(new HashMap<>()); functionConfig.setAutoAck(true); functionConfig.setTimeoutMs(2000L); functionConfig.setWindowConfig(new WindowConfig().setWindowLengthCount(10)); ProducerConfig producerConfig = new ProducerConfig(); producerConfig.setMaxPendingMessages(100); producerConfig.setMaxPendingMessagesAcrossPartitions(1000); producerConfig.setUseThreadLocalProducers(true); producerConfig.setBatchBuilder("KEY_BASED"); producerConfig.setCompressionType(CompressionType.SNAPPY); functionConfig.setProducerConfig(producerConfig); Function.FunctionDetails functionDetails = FunctionConfigUtils.convert(functionConfig); FunctionConfig convertedConfig = FunctionConfigUtils.convertFromDetails(functionDetails); // WindowsFunction guarantees convert to FunctionGuarantees. assertEquals(convertedConfig.getWindowConfig().getProcessingGuarantees(), WindowConfig.ProcessingGuarantees.valueOf(functionConfig.getProcessingGuarantees().name())); // add default resources functionConfig.setResources(Resources.getDefaultResources()); // set default cleanupSubscription config functionConfig.setCleanupSubscription(true); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(convertedConfig) ); } @Test public void testConvertBatchBuilder() { FunctionConfig functionConfig = createFunctionConfig(); functionConfig.setBatchBuilder("KEY_BASED"); Function.FunctionDetails functionDetails = FunctionConfigUtils.convert(functionConfig); assertEquals(functionDetails.getSink().getProducerSpec().getBatchBuilder(), "KEY_BASED"); FunctionConfig convertedConfig = FunctionConfigUtils.convertFromDetails(functionDetails); assertEquals(convertedConfig.getProducerConfig().getBatchBuilder(), "KEY_BASED"); } @Test public void testMergeEqual() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createFunctionConfig(); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Function Names differ") public void testMergeDifferentName() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("name", "Different"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Tenants differ") public void testMergeDifferentTenant() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("tenant", "Different"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Namespaces differ") public void testMergeDifferentNamespace() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("namespace", "Different"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testMergeDifferentClassName() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("className", "Different"); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getClassName(), "Different" ); mergedConfig.setClassName(functionConfig.getClassName()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Input Topics cannot be altered") public void testMergeDifferentInputs() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("topicsPattern", "Different"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "isRegexPattern for input topic test-input cannot be altered") public void testMergeDifferentInputSpecWithRegexChange() { FunctionConfig functionConfig = createFunctionConfig(); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(false) .serdeClassName("my-serde").build()); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("inputSpecs", inputSpecs); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testMergeDifferentInputSpec() { FunctionConfig functionConfig = createFunctionConfig(); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true) .serdeClassName("test-serde").receiverQueueSize(58).build()); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("inputSpecs", inputSpecs); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals(mergedConfig.getInputSpecs().get("test-input"), newFunctionConfig.getInputSpecs().get("test-input")); } @Test public void testMergeDifferentLogTopic() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("logTopic", "Different"); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getLogTopic(), "Different" ); mergedConfig.setLogTopic(functionConfig.getLogTopic()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeCleanupSubscription() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("cleanupSubscription", true); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertTrue(mergedConfig.getCleanupSubscription()); newFunctionConfig = createUpdatedFunctionConfig("cleanupSubscription", false); mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertFalse(mergedConfig.getCleanupSubscription()); newFunctionConfig = createUpdatedFunctionConfig("cleanupSubscription", true); mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertTrue(mergedConfig.getCleanupSubscription()); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Processing Guarantees cannot be altered") public void testMergeDifferentProcessingGuarantees() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("processingGuarantees", EFFECTIVELY_ONCE); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Ordering cannot be altered") public void testMergeDifferentRetainOrdering() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("retainOrdering", true); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Retain Key Ordering cannot be altered") public void testMergeDifferentRetainKeyOrdering() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("retainKeyOrdering", true); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testMergeDifferentUserConfig() { FunctionConfig functionConfig = createFunctionConfig(); Map<String, String> myConfig = new HashMap<>(); myConfig.put("MyKey", "MyValue"); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("userConfig", myConfig); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getUserConfig(), myConfig ); mergedConfig.setUserConfig(functionConfig.getUserConfig()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentSecrets() { FunctionConfig functionConfig = createFunctionConfig(); Map<String, String> mySecrets = new HashMap<>(); mySecrets.put("MyKey", "MyValue"); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("secrets", mySecrets); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getSecrets(), mySecrets ); mergedConfig.setSecrets(functionConfig.getSecrets()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Runtime cannot be altered") public void testMergeDifferentRuntime() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("runtime", PYTHON); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "AutoAck cannot be altered") public void testMergeDifferentAutoAck() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("autoAck", false); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testMergeDifferentMaxMessageRetries() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("maxMessageRetries", 10); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getMaxMessageRetries(), Integer.valueOf(10) ); mergedConfig.setMaxMessageRetries(functionConfig.getMaxMessageRetries()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentDeadLetterTopic() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("deadLetterTopic", "Different"); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getDeadLetterTopic(), "Different" ); mergedConfig.setDeadLetterTopic(functionConfig.getDeadLetterTopic()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Subscription Name cannot be altered") public void testMergeDifferentSubname() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("subName", "Different"); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testMergeDifferentParallelism() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("parallelism", 101); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getParallelism(), Integer.valueOf(101) ); mergedConfig.setParallelism(functionConfig.getParallelism()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentResources() { FunctionConfig functionConfig = createFunctionConfig(); Resources resources = new Resources(); resources.setCpu(0.3); resources.setRam(1232L); resources.setDisk(123456L); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("resources", resources); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getResources(), resources ); mergedConfig.setResources(functionConfig.getResources()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentWindowConfig() { FunctionConfig functionConfig = createFunctionConfig(); WindowConfig windowConfig = new WindowConfig(); windowConfig.setSlidingIntervalCount(123); windowConfig.setSlidingIntervalDurationMs(123L); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("windowConfig", windowConfig); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getWindowConfig(), windowConfig ); mergedConfig.setWindowConfig(functionConfig.getWindowConfig()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentProducerConfig() { FunctionConfig functionConfig = createFunctionConfig(); ProducerConfig producerConfig = new ProducerConfig(); producerConfig.setMaxPendingMessages(100); producerConfig.setMaxPendingMessagesAcrossPartitions(1000); producerConfig.setUseThreadLocalProducers(true); producerConfig.setBatchBuilder("DEFAULT"); producerConfig.setCompressionType(CompressionType.ZLIB); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("producerConfig", producerConfig); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getProducerConfig(), producerConfig ); mergedConfig.setProducerConfig(functionConfig.getProducerConfig()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeDifferentTimeout() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("timeoutMs", 102L); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getTimeoutMs(), Long.valueOf(102L) ); mergedConfig.setTimeoutMs(functionConfig.getTimeoutMs()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } @Test public void testMergeRuntimeFlags() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("runtimeFlags", "-Dfoo=bar2"); FunctionConfig mergedConfig = FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); assertEquals( mergedConfig.getRuntimeFlags(), "-Dfoo=bar2" ); mergedConfig.setRuntimeFlags(functionConfig.getRuntimeFlags()); assertEquals( new Gson().toJson(functionConfig), new Gson().toJson(mergedConfig) ); } private FunctionConfig createFunctionConfig() { FunctionConfig functionConfig = new FunctionConfig(); functionConfig.setTenant("test-tenant"); functionConfig.setNamespace("test-namespace"); functionConfig.setName("test-function"); functionConfig.setParallelism(1); functionConfig.setClassName(IdentityFunction.class.getName()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true) .serdeClassName("test-serde").build()); functionConfig.setInputSpecs(inputSpecs); functionConfig.setOutput("test-output"); functionConfig.setOutputSerdeClassName("test-serde"); functionConfig.setOutputSchemaType("json"); functionConfig.setRuntime(FunctionConfig.Runtime.JAVA); functionConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE); functionConfig.setRetainOrdering(false); functionConfig.setRetainKeyOrdering(false); functionConfig.setSubscriptionPosition(SubscriptionInitialPosition.Earliest); functionConfig.setBatchBuilder("DEFAULT"); functionConfig.setForwardSourceMessageProperty(false); functionConfig.setUserConfig(new HashMap<>()); functionConfig.setAutoAck(true); functionConfig.setTimeoutMs(2000L); functionConfig.setCleanupSubscription(true); functionConfig.setRuntimeFlags("-Dfoo=bar"); return functionConfig; } private FunctionConfig createUpdatedFunctionConfig(String fieldName, Object fieldValue) { FunctionConfig functionConfig = createFunctionConfig(); Class<?> fClass = FunctionConfig.class; try { Field chap = fClass.getDeclaredField(fieldName); chap.setAccessible(true); chap.set(functionConfig, fieldValue); } catch (Exception e) { throw new RuntimeException("Something wrong with the test", e); } return functionConfig; } @Test public void testDisableForwardSourceMessageProperty() throws InvalidProtocolBufferException { FunctionConfig config = new FunctionConfig(); config.setTenant("test-tenant"); config.setNamespace("test-namespace"); config.setName("test-function"); config.setParallelism(1); config.setClassName(IdentityFunction.class.getName()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder().isRegexPattern(true) .serdeClassName("test-serde").build()); config.setInputSpecs(inputSpecs); config.setOutput("test-output"); config.setForwardSourceMessageProperty(true); FunctionConfigUtils.inferMissingArguments(config, false); assertNull(config.getForwardSourceMessageProperty()); FunctionDetails details = FunctionConfigUtils.convert(config); assertFalse(details.getSink().getForwardSourceMessageProperty()); String detailsJson = "'" + JsonFormat.printer().omittingInsignificantWhitespace().print(details) + "'"; log.info("Function details : {}", detailsJson); assertFalse(detailsJson.contains("forwardSourceMessageProperty")); } @Test public void testFunctionConfigConvertFromDetails() { String name = "test1"; String namespace = "ns1"; String tenant = "tenant1"; String classname = getClass().getName(); int parallelism = 3; Map<String, String> userConfig = new HashMap<>(); userConfig.put("key1", "val1"); Function.ProcessingGuarantees processingGuarantees = Function.ProcessingGuarantees.EFFECTIVELY_ONCE; Function.FunctionDetails.Runtime runtime = Function.FunctionDetails.Runtime.JAVA; Function.SinkSpec sinkSpec = Function.SinkSpec.newBuilder().setTopic("sinkTopic1").build(); Map<String, Function.ConsumerSpec> consumerSpecMap = new HashMap<>(); consumerSpecMap.put("sourceTopic1", Function.ConsumerSpec.newBuilder() .setSchemaType(JSONSchema.class.getName()).build()); Function.SourceSpec sourceSpec = Function.SourceSpec.newBuilder() .putAllInputSpecs(consumerSpecMap) .setSubscriptionType(Function.SubscriptionType.FAILOVER) .setCleanupSubscription(true) .build(); boolean autoAck = true; String logTopic = "log-topic1"; Function.Resources resources = Function.Resources.newBuilder().setCpu(1.5).setDisk(1024 * 20).setRam(1024 * 10).build(); String packageUrl = "http://package.url"; Map<String, String> secretsMap = new HashMap<>(); secretsMap.put("secretConfigKey1", "secretConfigVal1"); Function.RetryDetails retryDetails = Function.RetryDetails.newBuilder().setDeadLetterTopic("dead-letter-1").build(); Function.FunctionDetails functionDetails = Function.FunctionDetails .newBuilder() .setNamespace(namespace) .setTenant(tenant) .setName(name) .setClassName(classname) .setParallelism(parallelism) .setUserConfig(new Gson().toJson(userConfig)) .setProcessingGuarantees(processingGuarantees) .setRuntime(runtime) .setSink(sinkSpec) .setSource(sourceSpec) .setAutoAck(autoAck) .setLogTopic(logTopic) .setResources(resources) .setPackageUrl(packageUrl) .setSecretsMap(new Gson().toJson(secretsMap)) .setRetryDetails(retryDetails) .build(); FunctionConfig functionConfig = FunctionConfigUtils.convertFromDetails(functionDetails); assertEquals(functionConfig.getTenant(), tenant); assertEquals(functionConfig.getNamespace(), namespace); assertEquals(functionConfig.getName(), name); assertEquals(functionConfig.getClassName(), classname); assertEquals(functionConfig.getLogTopic(), logTopic); assertEquals((Object) functionConfig.getResources().getCpu(), resources.getCpu()); assertEquals(functionConfig.getResources().getDisk().longValue(), resources.getDisk()); assertEquals(functionConfig.getResources().getRam().longValue(), resources.getRam()); assertEquals(functionConfig.getOutput(), sinkSpec.getTopic()); assertEquals(functionConfig.getInputSpecs().keySet(), sourceSpec.getInputSpecsMap().keySet()); assertEquals(functionConfig.getCleanupSubscription().booleanValue(), sourceSpec.getCleanupSubscription()); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Output Serde mismatch") public void testMergeDifferentSerde() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("outputSerdeClassName", "test-updated-serde"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Output Schema mismatch") public void testMergeDifferentOutputSchemaTypes() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("outputSchemaType", "avro"); FunctionConfigUtils.validateUpdate(functionConfig, newFunctionConfig); } @Test public void testPoolMessages() { FunctionConfig functionConfig = createFunctionConfig(); Function.FunctionDetails functionDetails = FunctionConfigUtils.convert(functionConfig); assertFalse(functionDetails.getSource().getInputSpecsMap().get("test-input").getPoolMessages()); FunctionConfig convertedConfig = FunctionConfigUtils.convertFromDetails(functionDetails); assertFalse(convertedConfig.getInputSpecs().get("test-input").isPoolMessages()); Map<String, ConsumerConfig> inputSpecs = new HashMap<>(); inputSpecs.put("test-input", ConsumerConfig.builder() .poolMessages(true).build()); functionConfig.setInputSpecs(inputSpecs); functionDetails = FunctionConfigUtils.convert(functionConfig); assertTrue(functionDetails.getSource().getInputSpecsMap().get("test-input").getPoolMessages()); convertedConfig = FunctionConfigUtils.convertFromDetails(functionDetails); assertTrue(convertedConfig.getInputSpecs().get("test-input").isPoolMessages()); } @Test public void testConvertProducerSpecToProducerConfigAndBackToProducerSpec() { // given Function.ProducerSpec producerSpec = Function.ProducerSpec.newBuilder() .setBatchBuilder("KEY_BASED") .setCompressionType(Function.CompressionType.ZSTD) .setCryptoSpec(Function.CryptoSpec.newBuilder() .addProducerEncryptionKeyName("key1") .addProducerEncryptionKeyName("key2") .setConsumerCryptoFailureAction(Function.CryptoSpec.FailureAction.DISCARD) .setProducerCryptoFailureAction(Function.CryptoSpec.FailureAction.SEND) .setCryptoKeyReaderClassName("ReaderClassName") .setCryptoKeyReaderConfig("{\"key\":\"value\"}") .build()) .build(); // when ProducerConfig producerConfig = FunctionConfigUtils.convertProducerSpecToProducerConfig(producerSpec); // then assertEquals(producerConfig.getBatchBuilder(), "KEY_BASED"); assertEquals(producerConfig.getCompressionType(), CompressionType.ZSTD); CryptoConfig cryptoConfig = producerConfig.getCryptoConfig(); assertEquals(cryptoConfig.getProducerCryptoFailureAction(), ProducerCryptoFailureAction.SEND); assertEquals(cryptoConfig.getConsumerCryptoFailureAction(), ConsumerCryptoFailureAction.DISCARD); assertEquals(cryptoConfig.getEncryptionKeys(), new String[]{"key1", "key2"}); assertEquals(cryptoConfig.getCryptoKeyReaderClassName(), "ReaderClassName"); // and when // converted back to producer spec Function.ProducerSpec producerSpec2 = FunctionConfigUtils.convertProducerConfigToProducerSpec(producerConfig); // then assertEquals(producerSpec2, producerSpec); } }
googleapis/google-cloud-java
35,331
java-notebooks/proto-google-cloud-notebooks-v1/src/main/java/com/google/cloud/notebooks/v1/CreateScheduleRequest.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/notebooks/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.notebooks.v1; /** * * * <pre> * Request for created scheduled notebooks * </pre> * * Protobuf type {@code google.cloud.notebooks.v1.CreateScheduleRequest} */ public final class CreateScheduleRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1.CreateScheduleRequest) CreateScheduleRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateScheduleRequest.newBuilder() to construct. private CreateScheduleRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateScheduleRequest() { parent_ = ""; scheduleId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateScheduleRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.notebooks.v1.NotebooksProto .internal_static_google_cloud_notebooks_v1_CreateScheduleRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.notebooks.v1.NotebooksProto .internal_static_google_cloud_notebooks_v1_CreateScheduleRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.notebooks.v1.CreateScheduleRequest.class, com.google.cloud.notebooks.v1.CreateScheduleRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Format: * `parent=projects/{project_id}/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. Format: * `parent=projects/{project_id}/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 SCHEDULE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object scheduleId_ = ""; /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The scheduleId. */ @java.lang.Override public java.lang.String getScheduleId() { java.lang.Object ref = scheduleId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); scheduleId_ = s; return s; } } /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for scheduleId. */ @java.lang.Override public com.google.protobuf.ByteString getScheduleIdBytes() { java.lang.Object ref = scheduleId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); scheduleId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SCHEDULE_FIELD_NUMBER = 3; private com.google.cloud.notebooks.v1.Schedule schedule_; /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the schedule field is set. */ @java.lang.Override public boolean hasSchedule() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The schedule. */ @java.lang.Override public com.google.cloud.notebooks.v1.Schedule getSchedule() { return schedule_ == null ? com.google.cloud.notebooks.v1.Schedule.getDefaultInstance() : schedule_; } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.notebooks.v1.ScheduleOrBuilder getScheduleOrBuilder() { return schedule_ == null ? com.google.cloud.notebooks.v1.Schedule.getDefaultInstance() : schedule_; } 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(scheduleId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, scheduleId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getSchedule()); } 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(scheduleId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, scheduleId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getSchedule()); } 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.notebooks.v1.CreateScheduleRequest)) { return super.equals(obj); } com.google.cloud.notebooks.v1.CreateScheduleRequest other = (com.google.cloud.notebooks.v1.CreateScheduleRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getScheduleId().equals(other.getScheduleId())) return false; if (hasSchedule() != other.hasSchedule()) return false; if (hasSchedule()) { if (!getSchedule().equals(other.getSchedule())) 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) + SCHEDULE_ID_FIELD_NUMBER; hash = (53 * hash) + getScheduleId().hashCode(); if (hasSchedule()) { hash = (37 * hash) + SCHEDULE_FIELD_NUMBER; hash = (53 * hash) + getSchedule().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.notebooks.v1.CreateScheduleRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest 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.notebooks.v1.CreateScheduleRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest 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.notebooks.v1.CreateScheduleRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest 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.notebooks.v1.CreateScheduleRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest 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.notebooks.v1.CreateScheduleRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest 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.notebooks.v1.CreateScheduleRequest 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 created scheduled notebooks * </pre> * * Protobuf type {@code google.cloud.notebooks.v1.CreateScheduleRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1.CreateScheduleRequest) com.google.cloud.notebooks.v1.CreateScheduleRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.notebooks.v1.NotebooksProto .internal_static_google_cloud_notebooks_v1_CreateScheduleRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.notebooks.v1.NotebooksProto .internal_static_google_cloud_notebooks_v1_CreateScheduleRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.notebooks.v1.CreateScheduleRequest.class, com.google.cloud.notebooks.v1.CreateScheduleRequest.Builder.class); } // Construct using com.google.cloud.notebooks.v1.CreateScheduleRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getScheduleFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; scheduleId_ = ""; schedule_ = null; if (scheduleBuilder_ != null) { scheduleBuilder_.dispose(); scheduleBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.notebooks.v1.NotebooksProto .internal_static_google_cloud_notebooks_v1_CreateScheduleRequest_descriptor; } @java.lang.Override public com.google.cloud.notebooks.v1.CreateScheduleRequest getDefaultInstanceForType() { return com.google.cloud.notebooks.v1.CreateScheduleRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.notebooks.v1.CreateScheduleRequest build() { com.google.cloud.notebooks.v1.CreateScheduleRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.notebooks.v1.CreateScheduleRequest buildPartial() { com.google.cloud.notebooks.v1.CreateScheduleRequest result = new com.google.cloud.notebooks.v1.CreateScheduleRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.notebooks.v1.CreateScheduleRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.scheduleId_ = scheduleId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.schedule_ = scheduleBuilder_ == null ? schedule_ : scheduleBuilder_.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.notebooks.v1.CreateScheduleRequest) { return mergeFrom((com.google.cloud.notebooks.v1.CreateScheduleRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.notebooks.v1.CreateScheduleRequest other) { if (other == com.google.cloud.notebooks.v1.CreateScheduleRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getScheduleId().isEmpty()) { scheduleId_ = other.scheduleId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasSchedule()) { mergeSchedule(other.getSchedule()); } 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: { scheduleId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getScheduleFieldBuilder().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. Format: * `parent=projects/{project_id}/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. Format: * `parent=projects/{project_id}/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. Format: * `parent=projects/{project_id}/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. Format: * `parent=projects/{project_id}/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. Format: * `parent=projects/{project_id}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object scheduleId_ = ""; /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The scheduleId. */ public java.lang.String getScheduleId() { java.lang.Object ref = scheduleId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); scheduleId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for scheduleId. */ public com.google.protobuf.ByteString getScheduleIdBytes() { java.lang.Object ref = scheduleId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); scheduleId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The scheduleId to set. * @return This builder for chaining. */ public Builder setScheduleId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } scheduleId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearScheduleId() { scheduleId_ = getDefaultInstance().getScheduleId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. User-defined unique ID of this schedule. * </pre> * * <code>string schedule_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for scheduleId to set. * @return This builder for chaining. */ public Builder setScheduleIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); scheduleId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.notebooks.v1.Schedule schedule_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.notebooks.v1.Schedule, com.google.cloud.notebooks.v1.Schedule.Builder, com.google.cloud.notebooks.v1.ScheduleOrBuilder> scheduleBuilder_; /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the schedule field is set. */ public boolean hasSchedule() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The schedule. */ public com.google.cloud.notebooks.v1.Schedule getSchedule() { if (scheduleBuilder_ == null) { return schedule_ == null ? com.google.cloud.notebooks.v1.Schedule.getDefaultInstance() : schedule_; } else { return scheduleBuilder_.getMessage(); } } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSchedule(com.google.cloud.notebooks.v1.Schedule value) { if (scheduleBuilder_ == null) { if (value == null) { throw new NullPointerException(); } schedule_ = value; } else { scheduleBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setSchedule(com.google.cloud.notebooks.v1.Schedule.Builder builderForValue) { if (scheduleBuilder_ == null) { schedule_ = builderForValue.build(); } else { scheduleBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeSchedule(com.google.cloud.notebooks.v1.Schedule value) { if (scheduleBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && schedule_ != null && schedule_ != com.google.cloud.notebooks.v1.Schedule.getDefaultInstance()) { getScheduleBuilder().mergeFrom(value); } else { schedule_ = value; } } else { scheduleBuilder_.mergeFrom(value); } if (schedule_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearSchedule() { bitField0_ = (bitField0_ & ~0x00000004); schedule_ = null; if (scheduleBuilder_ != null) { scheduleBuilder_.dispose(); scheduleBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.notebooks.v1.Schedule.Builder getScheduleBuilder() { bitField0_ |= 0x00000004; onChanged(); return getScheduleFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.notebooks.v1.ScheduleOrBuilder getScheduleOrBuilder() { if (scheduleBuilder_ != null) { return scheduleBuilder_.getMessageOrBuilder(); } else { return schedule_ == null ? com.google.cloud.notebooks.v1.Schedule.getDefaultInstance() : schedule_; } } /** * * * <pre> * Required. The schedule to be created. * </pre> * * <code> * .google.cloud.notebooks.v1.Schedule schedule = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.notebooks.v1.Schedule, com.google.cloud.notebooks.v1.Schedule.Builder, com.google.cloud.notebooks.v1.ScheduleOrBuilder> getScheduleFieldBuilder() { if (scheduleBuilder_ == null) { scheduleBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.notebooks.v1.Schedule, com.google.cloud.notebooks.v1.Schedule.Builder, com.google.cloud.notebooks.v1.ScheduleOrBuilder>( getSchedule(), getParentForChildren(), isClean()); schedule_ = null; } return scheduleBuilder_; } @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.notebooks.v1.CreateScheduleRequest) } // @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1.CreateScheduleRequest) private static final com.google.cloud.notebooks.v1.CreateScheduleRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1.CreateScheduleRequest(); } public static com.google.cloud.notebooks.v1.CreateScheduleRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateScheduleRequest> PARSER = new com.google.protobuf.AbstractParser<CreateScheduleRequest>() { @java.lang.Override public CreateScheduleRequest 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<CreateScheduleRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateScheduleRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.notebooks.v1.CreateScheduleRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,408
java-geminidataanalytics/proto-google-cloud-geminidataanalytics-v1beta/src/main/java/com/google/cloud/geminidataanalytics/v1beta/StudioDatasourceReferences.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/geminidataanalytics/v1beta/datasource.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.geminidataanalytics.v1beta; /** * * * <pre> * Message representing references to Looker Studio datasources. * </pre> * * Protobuf type {@code google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences} */ public final class StudioDatasourceReferences extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) StudioDatasourceReferencesOrBuilder { private static final long serialVersionUID = 0L; // Use StudioDatasourceReferences.newBuilder() to construct. private StudioDatasourceReferences(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private StudioDatasourceReferences() { studioReferences_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new StudioDatasourceReferences(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.geminidataanalytics.v1beta.DatasourceProto .internal_static_google_cloud_geminidataanalytics_v1beta_StudioDatasourceReferences_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.geminidataanalytics.v1beta.DatasourceProto .internal_static_google_cloud_geminidataanalytics_v1beta_StudioDatasourceReferences_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences.class, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences.Builder.class); } public static final int STUDIO_REFERENCES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference> studioReferences_; /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference> getStudioReferencesList() { return studioReferences_; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder> getStudioReferencesOrBuilderList() { return studioReferences_; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ @java.lang.Override public int getStudioReferencesCount() { return studioReferences_.size(); } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference getStudioReferences( int index) { return studioReferences_.get(index); } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder getStudioReferencesOrBuilder(int index) { return studioReferences_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < studioReferences_.size(); i++) { output.writeMessage(2, studioReferences_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < studioReferences_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, studioReferences_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences)) { return super.equals(obj); } com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences other = (com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) obj; if (!getStudioReferencesList().equals(other.getStudioReferencesList())) 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 (getStudioReferencesCount() > 0) { hash = (37 * hash) + STUDIO_REFERENCES_FIELD_NUMBER; hash = (53 * hash) + getStudioReferencesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences 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.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences 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.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences 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.geminidataanalytics.v1beta.StudioDatasourceReferences parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences 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.geminidataanalytics.v1beta.StudioDatasourceReferences parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences 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.geminidataanalytics.v1beta.StudioDatasourceReferences 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 representing references to Looker Studio datasources. * </pre> * * Protobuf type {@code google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferencesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.geminidataanalytics.v1beta.DatasourceProto .internal_static_google_cloud_geminidataanalytics_v1beta_StudioDatasourceReferences_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.geminidataanalytics.v1beta.DatasourceProto .internal_static_google_cloud_geminidataanalytics_v1beta_StudioDatasourceReferences_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences.class, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences.Builder.class); } // Construct using // com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (studioReferencesBuilder_ == null) { studioReferences_ = java.util.Collections.emptyList(); } else { studioReferences_ = null; studioReferencesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.geminidataanalytics.v1beta.DatasourceProto .internal_static_google_cloud_geminidataanalytics_v1beta_StudioDatasourceReferences_descriptor; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences getDefaultInstanceForType() { return com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences .getDefaultInstance(); } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences build() { com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences buildPartial() { com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences result = new com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences result) { if (studioReferencesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { studioReferences_ = java.util.Collections.unmodifiableList(studioReferences_); bitField0_ = (bitField0_ & ~0x00000001); } result.studioReferences_ = studioReferences_; } else { result.studioReferences_ = studioReferencesBuilder_.build(); } } private void buildPartial0( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) { return mergeFrom( (com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences other) { if (other == com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences .getDefaultInstance()) return this; if (studioReferencesBuilder_ == null) { if (!other.studioReferences_.isEmpty()) { if (studioReferences_.isEmpty()) { studioReferences_ = other.studioReferences_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureStudioReferencesIsMutable(); studioReferences_.addAll(other.studioReferences_); } onChanged(); } } else { if (!other.studioReferences_.isEmpty()) { if (studioReferencesBuilder_.isEmpty()) { studioReferencesBuilder_.dispose(); studioReferencesBuilder_ = null; studioReferences_ = other.studioReferences_; bitField0_ = (bitField0_ & ~0x00000001); studioReferencesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getStudioReferencesFieldBuilder() : null; } else { studioReferencesBuilder_.addAllMessages(other.studioReferences_); } } } 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: { com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference m = input.readMessage( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference .parser(), extensionRegistry); if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); studioReferences_.add(m); } else { studioReferencesBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference> studioReferences_ = java.util.Collections.emptyList(); private void ensureStudioReferencesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { studioReferences_ = new java.util.ArrayList< com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference>( studioReferences_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder> studioReferencesBuilder_; /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public java.util.List<com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference> getStudioReferencesList() { if (studioReferencesBuilder_ == null) { return java.util.Collections.unmodifiableList(studioReferences_); } else { return studioReferencesBuilder_.getMessageList(); } } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public int getStudioReferencesCount() { if (studioReferencesBuilder_ == null) { return studioReferences_.size(); } else { return studioReferencesBuilder_.getCount(); } } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference getStudioReferences(int index) { if (studioReferencesBuilder_ == null) { return studioReferences_.get(index); } else { return studioReferencesBuilder_.getMessage(index); } } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder setStudioReferences( int index, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference value) { if (studioReferencesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStudioReferencesIsMutable(); studioReferences_.set(index, value); onChanged(); } else { studioReferencesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder setStudioReferences( int index, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder builderForValue) { if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); studioReferences_.set(index, builderForValue.build()); onChanged(); } else { studioReferencesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder addStudioReferences( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference value) { if (studioReferencesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStudioReferencesIsMutable(); studioReferences_.add(value); onChanged(); } else { studioReferencesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder addStudioReferences( int index, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference value) { if (studioReferencesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStudioReferencesIsMutable(); studioReferences_.add(index, value); onChanged(); } else { studioReferencesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder addStudioReferences( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder builderForValue) { if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); studioReferences_.add(builderForValue.build()); onChanged(); } else { studioReferencesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder addStudioReferences( int index, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder builderForValue) { if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); studioReferences_.add(index, builderForValue.build()); onChanged(); } else { studioReferencesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder addAllStudioReferences( java.lang.Iterable< ? extends com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference> values) { if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, studioReferences_); onChanged(); } else { studioReferencesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder clearStudioReferences() { if (studioReferencesBuilder_ == null) { studioReferences_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { studioReferencesBuilder_.clear(); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public Builder removeStudioReferences(int index) { if (studioReferencesBuilder_ == null) { ensureStudioReferencesIsMutable(); studioReferences_.remove(index); onChanged(); } else { studioReferencesBuilder_.remove(index); } return this; } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder getStudioReferencesBuilder(int index) { return getStudioReferencesFieldBuilder().getBuilder(index); } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder getStudioReferencesOrBuilder(int index) { if (studioReferencesBuilder_ == null) { return studioReferences_.get(index); } else { return studioReferencesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public java.util.List< ? extends com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder> getStudioReferencesOrBuilderList() { if (studioReferencesBuilder_ != null) { return studioReferencesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(studioReferences_); } } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder addStudioReferencesBuilder() { return getStudioReferencesFieldBuilder() .addBuilder( com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference .getDefaultInstance()); } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder addStudioReferencesBuilder(int index) { return getStudioReferencesFieldBuilder() .addBuilder( index, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference .getDefaultInstance()); } /** * * * <pre> * The references to the studio datasources. * </pre> * * <code> * repeated .google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference studio_references = 2; * </code> */ public java.util.List< com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder> getStudioReferencesBuilderList() { return getStudioReferencesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder> getStudioReferencesFieldBuilder() { if (studioReferencesBuilder_ == null) { studioReferencesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReference.Builder, com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferenceOrBuilder>( studioReferences_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); studioReferences_ = null; } return studioReferencesBuilder_; } @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.geminidataanalytics.v1beta.StudioDatasourceReferences) } // @@protoc_insertion_point(class_scope:google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences) private static final com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences(); } public static com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<StudioDatasourceReferences> PARSER = new com.google.protobuf.AbstractParser<StudioDatasourceReferences>() { @java.lang.Override public StudioDatasourceReferences 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<StudioDatasourceReferences> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<StudioDatasourceReferences> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.geminidataanalytics.v1beta.StudioDatasourceReferences getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,360
java-dataproc/proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/ClusterMetrics.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/clusters.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataproc.v1; /** * * * <pre> * Contains cluster daemon metrics, such as HDFS and YARN stats. * * **Beta Feature**: This report is available for testing purposes only. It may * be changed before final release. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.ClusterMetrics} */ public final class ClusterMetrics extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.ClusterMetrics) ClusterMetricsOrBuilder { private static final long serialVersionUID = 0L; // Use ClusterMetrics.newBuilder() to construct. private ClusterMetrics(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ClusterMetrics() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ClusterMetrics(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 1: return internalGetHdfsMetrics(); case 2: return internalGetYarnMetrics(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.ClusterMetrics.class, com.google.cloud.dataproc.v1.ClusterMetrics.Builder.class); } public static final int HDFS_METRICS_FIELD_NUMBER = 1; private static final class HdfsMetricsDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.Long>newDefaultInstance( com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_HdfsMetricsEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.INT64, 0L); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.Long> hdfsMetrics_; private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetHdfsMetrics() { if (hdfsMetrics_ == null) { return com.google.protobuf.MapField.emptyMapField(HdfsMetricsDefaultEntryHolder.defaultEntry); } return hdfsMetrics_; } public int getHdfsMetricsCount() { return internalGetHdfsMetrics().getMap().size(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public boolean containsHdfsMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetHdfsMetrics().getMap().containsKey(key); } /** Use {@link #getHdfsMetricsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getHdfsMetrics() { return getHdfsMetricsMap(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.Long> getHdfsMetricsMap() { return internalGetHdfsMetrics().getMap(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public long getHdfsMetricsOrDefault(java.lang.String key, long defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetHdfsMetrics().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public long getHdfsMetricsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetHdfsMetrics().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public static final int YARN_METRICS_FIELD_NUMBER = 2; private static final class YarnMetricsDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.Long>newDefaultInstance( com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_YarnMetricsEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.INT64, 0L); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.Long> yarnMetrics_; private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetYarnMetrics() { if (yarnMetrics_ == null) { return com.google.protobuf.MapField.emptyMapField(YarnMetricsDefaultEntryHolder.defaultEntry); } return yarnMetrics_; } public int getYarnMetricsCount() { return internalGetYarnMetrics().getMap().size(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public boolean containsYarnMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetYarnMetrics().getMap().containsKey(key); } /** Use {@link #getYarnMetricsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getYarnMetrics() { return getYarnMetricsMap(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.Long> getYarnMetricsMap() { return internalGetYarnMetrics().getMap(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public long getYarnMetricsOrDefault(java.lang.String key, long defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetYarnMetrics().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public long getYarnMetricsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetYarnMetrics().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetHdfsMetrics(), HdfsMetricsDefaultEntryHolder.defaultEntry, 1); com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetYarnMetrics(), YarnMetricsDefaultEntryHolder.defaultEntry, 2); getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (java.util.Map.Entry<java.lang.String, java.lang.Long> entry : internalGetHdfsMetrics().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> hdfsMetrics__ = HdfsMetricsDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, hdfsMetrics__); } for (java.util.Map.Entry<java.lang.String, java.lang.Long> entry : internalGetYarnMetrics().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> yarnMetrics__ = YarnMetricsDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, yarnMetrics__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataproc.v1.ClusterMetrics)) { return super.equals(obj); } com.google.cloud.dataproc.v1.ClusterMetrics other = (com.google.cloud.dataproc.v1.ClusterMetrics) obj; if (!internalGetHdfsMetrics().equals(other.internalGetHdfsMetrics())) return false; if (!internalGetYarnMetrics().equals(other.internalGetYarnMetrics())) 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 (!internalGetHdfsMetrics().getMap().isEmpty()) { hash = (37 * hash) + HDFS_METRICS_FIELD_NUMBER; hash = (53 * hash) + internalGetHdfsMetrics().hashCode(); } if (!internalGetYarnMetrics().getMap().isEmpty()) { hash = (37 * hash) + YARN_METRICS_FIELD_NUMBER; hash = (53 * hash) + internalGetYarnMetrics().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataproc.v1.ClusterMetrics parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataproc.v1.ClusterMetrics 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> * Contains cluster daemon metrics, such as HDFS and YARN stats. * * **Beta Feature**: This report is available for testing purposes only. It may * be changed before final release. * </pre> * * Protobuf type {@code google.cloud.dataproc.v1.ClusterMetrics} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.ClusterMetrics) com.google.cloud.dataproc.v1.ClusterMetricsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 1: return internalGetHdfsMetrics(); case 2: return internalGetYarnMetrics(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 1: return internalGetMutableHdfsMetrics(); case 2: return internalGetMutableYarnMetrics(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataproc.v1.ClusterMetrics.class, com.google.cloud.dataproc.v1.ClusterMetrics.Builder.class); } // Construct using com.google.cloud.dataproc.v1.ClusterMetrics.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; internalGetMutableHdfsMetrics().clear(); internalGetMutableYarnMetrics().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataproc.v1.ClustersProto .internal_static_google_cloud_dataproc_v1_ClusterMetrics_descriptor; } @java.lang.Override public com.google.cloud.dataproc.v1.ClusterMetrics getDefaultInstanceForType() { return com.google.cloud.dataproc.v1.ClusterMetrics.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataproc.v1.ClusterMetrics build() { com.google.cloud.dataproc.v1.ClusterMetrics result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataproc.v1.ClusterMetrics buildPartial() { com.google.cloud.dataproc.v1.ClusterMetrics result = new com.google.cloud.dataproc.v1.ClusterMetrics(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dataproc.v1.ClusterMetrics result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.hdfsMetrics_ = internalGetHdfsMetrics(); result.hdfsMetrics_.makeImmutable(); } if (((from_bitField0_ & 0x00000002) != 0)) { result.yarnMetrics_ = internalGetYarnMetrics(); result.yarnMetrics_.makeImmutable(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataproc.v1.ClusterMetrics) { return mergeFrom((com.google.cloud.dataproc.v1.ClusterMetrics) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataproc.v1.ClusterMetrics other) { if (other == com.google.cloud.dataproc.v1.ClusterMetrics.getDefaultInstance()) return this; internalGetMutableHdfsMetrics().mergeFrom(other.internalGetHdfsMetrics()); bitField0_ |= 0x00000001; internalGetMutableYarnMetrics().mergeFrom(other.internalGetYarnMetrics()); bitField0_ |= 0x00000002; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> hdfsMetrics__ = input.readMessage( HdfsMetricsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableHdfsMetrics() .getMutableMap() .put(hdfsMetrics__.getKey(), hdfsMetrics__.getValue()); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.protobuf.MapEntry<java.lang.String, java.lang.Long> yarnMetrics__ = input.readMessage( YarnMetricsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableYarnMetrics() .getMutableMap() .put(yarnMetrics__.getKey(), yarnMetrics__.getValue()); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.MapField<java.lang.String, java.lang.Long> hdfsMetrics_; private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetHdfsMetrics() { if (hdfsMetrics_ == null) { return com.google.protobuf.MapField.emptyMapField( HdfsMetricsDefaultEntryHolder.defaultEntry); } return hdfsMetrics_; } private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetMutableHdfsMetrics() { if (hdfsMetrics_ == null) { hdfsMetrics_ = com.google.protobuf.MapField.newMapField(HdfsMetricsDefaultEntryHolder.defaultEntry); } if (!hdfsMetrics_.isMutable()) { hdfsMetrics_ = hdfsMetrics_.copy(); } bitField0_ |= 0x00000001; onChanged(); return hdfsMetrics_; } public int getHdfsMetricsCount() { return internalGetHdfsMetrics().getMap().size(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public boolean containsHdfsMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetHdfsMetrics().getMap().containsKey(key); } /** Use {@link #getHdfsMetricsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getHdfsMetrics() { return getHdfsMetricsMap(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.Long> getHdfsMetricsMap() { return internalGetHdfsMetrics().getMap(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public long getHdfsMetricsOrDefault(java.lang.String key, long defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetHdfsMetrics().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ @java.lang.Override public long getHdfsMetricsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetHdfsMetrics().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearHdfsMetrics() { bitField0_ = (bitField0_ & ~0x00000001); internalGetMutableHdfsMetrics().getMutableMap().clear(); return this; } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ public Builder removeHdfsMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableHdfsMetrics().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getMutableHdfsMetrics() { bitField0_ |= 0x00000001; return internalGetMutableHdfsMetrics().getMutableMap(); } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ public Builder putHdfsMetrics(java.lang.String key, long value) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableHdfsMetrics().getMutableMap().put(key, value); bitField0_ |= 0x00000001; return this; } /** * * * <pre> * The HDFS metrics. * </pre> * * <code>map&lt;string, int64&gt; hdfs_metrics = 1;</code> */ public Builder putAllHdfsMetrics(java.util.Map<java.lang.String, java.lang.Long> values) { internalGetMutableHdfsMetrics().getMutableMap().putAll(values); bitField0_ |= 0x00000001; return this; } private com.google.protobuf.MapField<java.lang.String, java.lang.Long> yarnMetrics_; private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetYarnMetrics() { if (yarnMetrics_ == null) { return com.google.protobuf.MapField.emptyMapField( YarnMetricsDefaultEntryHolder.defaultEntry); } return yarnMetrics_; } private com.google.protobuf.MapField<java.lang.String, java.lang.Long> internalGetMutableYarnMetrics() { if (yarnMetrics_ == null) { yarnMetrics_ = com.google.protobuf.MapField.newMapField(YarnMetricsDefaultEntryHolder.defaultEntry); } if (!yarnMetrics_.isMutable()) { yarnMetrics_ = yarnMetrics_.copy(); } bitField0_ |= 0x00000002; onChanged(); return yarnMetrics_; } public int getYarnMetricsCount() { return internalGetYarnMetrics().getMap().size(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public boolean containsYarnMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetYarnMetrics().getMap().containsKey(key); } /** Use {@link #getYarnMetricsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getYarnMetrics() { return getYarnMetricsMap(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.Long> getYarnMetricsMap() { return internalGetYarnMetrics().getMap(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public long getYarnMetricsOrDefault(java.lang.String key, long defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetYarnMetrics().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ @java.lang.Override public long getYarnMetricsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.Long> map = internalGetYarnMetrics().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearYarnMetrics() { bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableYarnMetrics().getMutableMap().clear(); return this; } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ public Builder removeYarnMetrics(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableYarnMetrics().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.Long> getMutableYarnMetrics() { bitField0_ |= 0x00000002; return internalGetMutableYarnMetrics().getMutableMap(); } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ public Builder putYarnMetrics(java.lang.String key, long value) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableYarnMetrics().getMutableMap().put(key, value); bitField0_ |= 0x00000002; return this; } /** * * * <pre> * YARN metrics. * </pre> * * <code>map&lt;string, int64&gt; yarn_metrics = 2;</code> */ public Builder putAllYarnMetrics(java.util.Map<java.lang.String, java.lang.Long> values) { internalGetMutableYarnMetrics().getMutableMap().putAll(values); bitField0_ |= 0x00000002; return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.ClusterMetrics) } // @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.ClusterMetrics) private static final com.google.cloud.dataproc.v1.ClusterMetrics DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.ClusterMetrics(); } public static com.google.cloud.dataproc.v1.ClusterMetrics getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ClusterMetrics> PARSER = new com.google.protobuf.AbstractParser<ClusterMetrics>() { @java.lang.Override public ClusterMetrics 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<ClusterMetrics> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ClusterMetrics> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataproc.v1.ClusterMetrics getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hudi
35,583
hudi-common/src/test/java/org/apache/hudi/common/table/view/TestPriorityBasedFileSystemView.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.common.table.view; import org.apache.hudi.common.engine.HoodieEngineContext; import org.apache.hudi.common.function.SerializableFunctionUnchecked; import org.apache.hudi.common.model.CompactionOperation; import org.apache.hudi.common.model.FileSlice; import org.apache.hudi.common.model.HoodieBaseFile; import org.apache.hudi.common.model.HoodieFileGroup; import org.apache.hudi.common.table.HoodieTableConfig; import org.apache.hudi.common.table.timeline.HoodieInstant; import org.apache.hudi.common.table.timeline.HoodieTimeline; import org.apache.hudi.common.testutils.HoodieTestUtils; import org.apache.hudi.common.testutils.MockHoodieTimeline; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.collection.ImmutablePair; import org.apache.hudi.common.util.collection.Pair; import org.apache.http.client.HttpResponseException; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests {@link PriorityBasedFileSystemView}. */ @ExtendWith(MockitoExtension.class) public class TestPriorityBasedFileSystemView { @Mock private HoodieEngineContext engineContext; @Mock private SyncableFileSystemView primary; @Mock private SyncableFileSystemView secondary; @Mock private SerializableFunctionUnchecked<HoodieEngineContext, SyncableFileSystemView> secondaryViewCreator; @InjectMocks private PriorityBasedFileSystemView fsView; private Stream<HoodieBaseFile> testBaseFileStream; private Stream<FileSlice> testFileSliceStream; @BeforeEach public void setUp() { fsView = new PriorityBasedFileSystemView(primary, secondaryViewCreator, engineContext); testBaseFileStream = Stream.of(new HoodieBaseFile("test")); testFileSliceStream = Stream.of(new FileSlice("2020-01-01", "20:20", "file0001" + HoodieTableConfig.BASE_FILE_FORMAT.defaultValue().getFileExtension())); } @AfterEach public void tearDown() throws Exception { testFileSliceStream.close(); testBaseFileStream.close(); fsView.close(); } private void resetMocks() { reset(primary, secondary); } @Test public void testGetLatestBaseFiles() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; when(primary.getLatestBaseFiles()).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFiles()).thenThrow(new RuntimeException()); when(secondary.getLatestBaseFiles()).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFiles()).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFiles()).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestBaseFiles(); }); } @Test public void testBadRequestExceptionWithPrimary() { final TestLogAppender appender = new TestLogAppender(); final Logger logger = (Logger) LogManager.getLogger(PriorityBasedFileSystemView.class); try { appender.start(); logger.addAppender(appender); Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFiles()).thenThrow(new RuntimeException(new HttpResponseException(400, "Bad Request"))); when(secondary.getLatestBaseFiles()).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(); assertEquals(expected, actual); final List<LogEvent> logs = appender.getLog(); final LogEvent firstLogEntry = logs.get(0); assertEquals(firstLogEntry.getLevel(), Level.WARN); assertTrue((firstLogEntry.getMessage().getFormattedMessage()).contains("Got error running preferred function. Likely due to another " + "concurrent writer in progress. Trying secondary")); } finally { logger.removeAppender(appender); } } @Test public void testGetLatestBaseFilesWithPartitionPath() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; String partitionPath = "/table2"; when(primary.getLatestBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFiles(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getLatestBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFiles(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFiles(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestBaseFiles(partitionPath); }); } @Test public void testGetLatestBaseFilesBeforeOrOn() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; String partitionPath = "/table2"; String maxCommitTime = "2010-10-10"; when(primary.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime)) .thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime)) .thenThrow(new RuntimeException()); when(secondary.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime)) .thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime)) .thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime)) .thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestBaseFilesBeforeOrOn(partitionPath, maxCommitTime); }); } @Test public void testGetLatestBaseFile() { Option<HoodieBaseFile> actual; Option<HoodieBaseFile> expected = Option.of(new HoodieBaseFile("test.file")); String partitionPath = "/table2"; String fileID = "file.123"; when(primary.getLatestBaseFile(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestBaseFile(partitionPath, fileID); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFile(partitionPath, fileID)).thenThrow(new RuntimeException()); when(secondary.getLatestBaseFile(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestBaseFile(partitionPath, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFile(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestBaseFile(partitionPath, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFile(partitionPath, fileID)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestBaseFile(partitionPath, fileID); }); } @Test public void testGetBaseFileOn() { Option<HoodieBaseFile> actual; Option<HoodieBaseFile> expected = Option.of(new HoodieBaseFile("test.file")); String partitionPath = "/table2"; String instantTime = "2020-01-01"; String fileID = "file.123"; when(primary.getBaseFileOn(partitionPath, instantTime, fileID)).thenReturn(expected); actual = fsView.getBaseFileOn(partitionPath, instantTime, fileID); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getBaseFileOn(partitionPath, instantTime, fileID)) .thenThrow(new RuntimeException()); when(secondary.getBaseFileOn(partitionPath, instantTime, fileID)).thenReturn(expected); actual = fsView.getBaseFileOn(partitionPath, instantTime, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getBaseFileOn(partitionPath, instantTime, fileID)).thenReturn(expected); actual = fsView.getBaseFileOn(partitionPath, instantTime, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getBaseFileOn(partitionPath, instantTime, fileID)) .thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getBaseFileOn(partitionPath, instantTime, fileID); }); } @Test public void testGetLatestBaseFilesInRange() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; List<String> commitsToReturn = Collections.singletonList("/table2"); when(primary.getLatestBaseFilesInRange(commitsToReturn)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesInRange(commitsToReturn); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestBaseFilesInRange(commitsToReturn)).thenThrow(new RuntimeException()); when(secondary.getLatestBaseFilesInRange(commitsToReturn)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesInRange(commitsToReturn); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFilesInRange(commitsToReturn)).thenReturn(testBaseFileStream); actual = fsView.getLatestBaseFilesInRange(commitsToReturn); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestBaseFilesInRange(commitsToReturn)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestBaseFilesInRange(commitsToReturn); }); } @Test public void testGetAllBaseFiles() { Stream<HoodieBaseFile> actual; Stream<HoodieBaseFile> expected = testBaseFileStream; String partitionPath = "/table2"; when(primary.getAllBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getAllBaseFiles(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getAllBaseFiles(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getAllBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getAllBaseFiles(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllBaseFiles(partitionPath)).thenReturn(testBaseFileStream); actual = fsView.getAllBaseFiles(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllBaseFiles(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getAllBaseFiles(partitionPath); }); } @Test public void testGetLatestFileSlices() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getLatestFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlices(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestFileSlices(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getLatestFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlices(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestFileSlices(partitionPath); }); } @Test public void testGetLatestFileSlicesIncludingInflight() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getLatestFileSlicesIncludingInflight(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesIncludingInflight(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestFileSlicesIncludingInflight(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getLatestFileSlicesIncludingInflight(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesIncludingInflight(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlicesIncludingInflight(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesIncludingInflight(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlicesIncludingInflight(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> fsView.getLatestFileSlicesIncludingInflight(partitionPath)); } @Test public void testGetLatestUnCompactedFileSlices() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getLatestUnCompactedFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestUnCompactedFileSlices(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestUnCompactedFileSlices(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getLatestUnCompactedFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestUnCompactedFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestUnCompactedFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getLatestUnCompactedFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestUnCompactedFileSlices(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestUnCompactedFileSlices(partitionPath); }); } @Test public void testGetLatestFileSlicesBeforeOrOn() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; String maxCommitTime = "2020-01-01"; when(primary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false)) .thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false)) .thenThrow(new RuntimeException()); when(secondary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false)) .thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false)) .thenReturn(testFileSliceStream); actual = fsView.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false)) .thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestFileSlicesBeforeOrOn(partitionPath, maxCommitTime, false); }); } @Test public void testGetLatestMergedFileSlicesBeforeOrOn() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; String maxInstantTime = "2020-01-01"; when(primary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) .thenReturn(testFileSliceStream); actual = fsView.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) .thenThrow(new RuntimeException()); when(secondary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) .thenReturn(testFileSliceStream); actual = fsView.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) .thenReturn(testFileSliceStream); actual = fsView.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime)) .thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestMergedFileSlicesBeforeOrOn(partitionPath, maxInstantTime); }); } @Test public void testGetLatestMergedFileSliceBeforeOrOn() { Option<FileSlice> actual; Option<FileSlice> expected = Option.fromJavaOptional(testFileSliceStream.findFirst()); String partitionPath = "/table2"; String maxInstantTime = "2020-01-01"; String fileId = UUID.randomUUID().toString(); when(primary.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId)) .thenReturn(expected); actual = fsView.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId)) .thenThrow(new RuntimeException()); when(secondary.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId)) .thenReturn(expected); actual = fsView.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId)) .thenReturn(expected); actual = fsView.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId)) .thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestMergedFileSliceBeforeOrOn(partitionPath, maxInstantTime, fileId); }); } @Test public void testGetLatestFileSliceInRange() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; List<String> commitsToReturn = Collections.singletonList("/table2"); when(primary.getLatestFileSliceInRange(commitsToReturn)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSliceInRange(commitsToReturn); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestFileSliceInRange(commitsToReturn)).thenThrow(new RuntimeException()); when(secondary.getLatestFileSliceInRange(commitsToReturn)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSliceInRange(commitsToReturn); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSliceInRange(commitsToReturn)).thenReturn(testFileSliceStream); actual = fsView.getLatestFileSliceInRange(commitsToReturn); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSliceInRange(commitsToReturn)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestFileSliceInRange(commitsToReturn); }); } @Test public void testGetAllFileSlices() { Stream<FileSlice> actual; Stream<FileSlice> expected = testFileSliceStream; String partitionPath = "/table2"; when(primary.getAllFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getAllFileSlices(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getAllFileSlices(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getAllFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getAllFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllFileSlices(partitionPath)).thenReturn(testFileSliceStream); actual = fsView.getAllFileSlices(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllFileSlices(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getAllFileSlices(partitionPath); }); } @Test public void testGetAllFileGroups() { Stream<HoodieFileGroup> actual; String partitionPath = "/table2"; Stream<HoodieFileGroup> expected = Collections.singleton( new HoodieFileGroup(partitionPath, "id1", new MockHoodieTimeline(Stream.empty(), Stream.empty()))).stream(); when(primary.getAllFileGroups(partitionPath)).thenReturn(expected); actual = fsView.getAllFileGroups(partitionPath); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getAllFileGroups(partitionPath)).thenThrow(new RuntimeException()); when(secondary.getAllFileGroups(partitionPath)).thenReturn(expected); actual = fsView.getAllFileGroups(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllFileGroups(partitionPath)).thenReturn(expected); actual = fsView.getAllFileGroups(partitionPath); assertEquals(expected, actual); resetMocks(); when(secondary.getAllFileGroups(partitionPath)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getAllFileGroups(partitionPath); }); } @Test public void testGetPendingCompactionOperations() { Stream<Pair<String, CompactionOperation>> actual; Stream<Pair<String, CompactionOperation>> expected = Collections.singleton( (Pair<String, CompactionOperation>) new ImmutablePair<>("test", new CompactionOperation())) .stream(); when(primary.getPendingCompactionOperations()).thenReturn(expected); actual = fsView.getPendingCompactionOperations(); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getPendingCompactionOperations()).thenThrow(new RuntimeException()); when(secondary.getPendingCompactionOperations()).thenReturn(expected); actual = fsView.getPendingCompactionOperations(); assertEquals(expected, actual); resetMocks(); when(secondary.getPendingCompactionOperations()).thenReturn(expected); actual = fsView.getPendingCompactionOperations(); assertEquals(expected, actual); resetMocks(); when(secondary.getPendingCompactionOperations()).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getPendingCompactionOperations(); }); } @Test public void testGetPendingLogCompactionOperations() { Stream<Pair<String, CompactionOperation>> actual; Stream<Pair<String, CompactionOperation>> expected = Collections.singleton( (Pair<String, CompactionOperation>) new ImmutablePair<>("test", new CompactionOperation())) .stream(); when(primary.getPendingLogCompactionOperations()).thenReturn(expected); actual = fsView.getPendingLogCompactionOperations(); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getPendingLogCompactionOperations()).thenThrow(new RuntimeException()); when(secondary.getPendingLogCompactionOperations()).thenReturn(expected); actual = fsView.getPendingLogCompactionOperations(); assertEquals(expected, actual); resetMocks(); when(secondary.getPendingLogCompactionOperations()).thenReturn(expected); actual = fsView.getPendingLogCompactionOperations(); assertEquals(expected, actual); resetMocks(); when(secondary.getPendingLogCompactionOperations()).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getPendingLogCompactionOperations(); }); } @Test public void testClose_noSecondaryInitialized() { fsView.close(); verify(primary, times(1)).close(); verify(secondary, never()).close(); } @Test public void testClose_withSecondaryInitialized() { // force secondary view to initialize when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); fsView.getSecondaryView(); fsView.close(); verify(primary, times(1)).close(); verify(secondary, times(1)).close(); } @Test public void testReset_noSecondaryInitialized() { fsView.reset(); verify(primary, times(1)).reset(); verify(secondary, never()).reset(); } @Test public void testReset_withSecondaryInitialized() { when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); fsView.getSecondaryView(); fsView.reset(); verify(primary, times(1)).reset(); verify(secondary, times(1)).reset(); } @Test public void testGetLastInstant() { Option<HoodieInstant> actual; Option<HoodieInstant> expected = Option.of(HoodieTestUtils.INSTANT_GENERATOR.createNewInstant(HoodieInstant.State.INFLIGHT, "", "")); when(primary.getLastInstant()).thenReturn(expected); actual = fsView.getLastInstant(); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLastInstant()).thenThrow(new RuntimeException()); when(secondary.getLastInstant()).thenReturn(expected); actual = fsView.getLastInstant(); assertEquals(expected, actual); resetMocks(); when(secondary.getLastInstant()).thenReturn(expected); actual = fsView.getLastInstant(); assertEquals(expected, actual); resetMocks(); when(secondary.getLastInstant()).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLastInstant(); }); } @Test public void testGetTimeline() { HoodieTimeline actual; HoodieTimeline expected = new MockHoodieTimeline(Stream.empty(), Stream.empty()); when(primary.getTimeline()).thenReturn(expected); actual = fsView.getTimeline(); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getTimeline()).thenThrow(new RuntimeException()); when(secondary.getTimeline()).thenReturn(expected); actual = fsView.getTimeline(); assertEquals(expected, actual); resetMocks(); when(secondary.getTimeline()).thenReturn(expected); actual = fsView.getTimeline(); assertEquals(expected, actual); resetMocks(); when(secondary.getTimeline()).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getTimeline(); }); } @Test public void testSync_noSecondaryInitialized() { fsView.sync(); verify(primary, times(1)).sync(); verify(secondary, never()).sync(); } @Test public void testSync_withSecondaryInitialized() { when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); fsView.getSecondaryView(); fsView.sync(); verify(primary, times(1)).sync(); verify(secondary, times(1)).sync(); } @Test public void testGetLatestFileSlice() { Option<FileSlice> actual; Option<FileSlice> expected = Option.fromJavaOptional(testFileSliceStream.findFirst()); String partitionPath = "/table2"; String fileID = "file.123"; when(primary.getLatestFileSlice(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestFileSlice(partitionPath, fileID); assertEquals(expected, actual); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); when(primary.getLatestFileSlice(partitionPath, fileID)).thenThrow(new RuntimeException()); when(secondary.getLatestFileSlice(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestFileSlice(partitionPath, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlice(partitionPath, fileID)).thenReturn(expected); actual = fsView.getLatestFileSlice(partitionPath, fileID); assertEquals(expected, actual); resetMocks(); when(secondary.getLatestFileSlice(partitionPath, fileID)).thenThrow(new RuntimeException()); assertThrows(RuntimeException.class, () -> { fsView.getLatestFileSlice(partitionPath, fileID); }); } @Test public void testLoadPartitions() { String partitionPath = "/table2"; fsView.loadPartitions(Collections.singletonList(partitionPath)); verify(primary, times(1)).loadPartitions(Collections.singletonList(partitionPath)); verify(secondary, never()).loadPartitions(any()); verify(secondaryViewCreator, never()).apply(engineContext); resetMocks(); when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); doThrow(new RuntimeException()).when(primary).loadPartitions(Collections.singletonList(partitionPath)); fsView.loadPartitions(Collections.singletonList(partitionPath)); verify(primary, times(1)).loadPartitions(Collections.singletonList(partitionPath)); verify(secondary, times(1)).loadPartitions(Collections.singletonList(partitionPath)); resetMocks(); doThrow(new RuntimeException()).when(secondary).loadPartitions(Collections.singletonList(partitionPath)); assertThrows(RuntimeException.class, () -> { fsView.loadPartitions(Collections.singletonList(partitionPath)); }); } @Test public void testGetPreferredView() { assertEquals(primary, fsView.getPreferredView()); } @Test public void testGetSecondaryView() { when(secondaryViewCreator.apply(engineContext)).thenReturn(secondary); assertEquals(secondary, fsView.getSecondaryView()); } class TestLogAppender extends AbstractAppender { private final List<LogEvent> log = new ArrayList<>(); protected TestLogAppender() { super(UUID.randomUUID().toString(), null, null, false, null); } @Override public void append(LogEvent event) { log.add(event.toImmutable()); } public List<LogEvent> getLog() { return new ArrayList<LogEvent>(log); } } }
googleapis/google-cloud-java
35,362
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/InterconnectCircuitInfo.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.compute.v1; /** * * * <pre> * Describes a single physical circuit between the Customer and Google. CircuitInfo objects are created by Google, so all fields are output only. * </pre> * * Protobuf type {@code google.cloud.compute.v1.InterconnectCircuitInfo} */ public final class InterconnectCircuitInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.InterconnectCircuitInfo) InterconnectCircuitInfoOrBuilder { private static final long serialVersionUID = 0L; // Use InterconnectCircuitInfo.newBuilder() to construct. private InterconnectCircuitInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InterconnectCircuitInfo() { customerDemarcId_ = ""; googleCircuitId_ = ""; googleDemarcId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new InterconnectCircuitInfo(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InterconnectCircuitInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InterconnectCircuitInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.InterconnectCircuitInfo.class, com.google.cloud.compute.v1.InterconnectCircuitInfo.Builder.class); } private int bitField0_; public static final int CUSTOMER_DEMARC_ID_FIELD_NUMBER = 28771859; @SuppressWarnings("serial") private volatile java.lang.Object customerDemarcId_ = ""; /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return Whether the customerDemarcId field is set. */ @java.lang.Override public boolean hasCustomerDemarcId() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return The customerDemarcId. */ @java.lang.Override public java.lang.String getCustomerDemarcId() { java.lang.Object ref = customerDemarcId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerDemarcId_ = s; return s; } } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return The bytes for customerDemarcId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerDemarcIdBytes() { java.lang.Object ref = customerDemarcId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); customerDemarcId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GOOGLE_CIRCUIT_ID_FIELD_NUMBER = 262014711; @SuppressWarnings("serial") private volatile java.lang.Object googleCircuitId_ = ""; /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return Whether the googleCircuitId field is set. */ @java.lang.Override public boolean hasGoogleCircuitId() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return The googleCircuitId. */ @java.lang.Override public java.lang.String getGoogleCircuitId() { java.lang.Object ref = googleCircuitId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); googleCircuitId_ = s; return s; } } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return The bytes for googleCircuitId. */ @java.lang.Override public com.google.protobuf.ByteString getGoogleCircuitIdBytes() { java.lang.Object ref = googleCircuitId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); googleCircuitId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GOOGLE_DEMARC_ID_FIELD_NUMBER = 448196270; @SuppressWarnings("serial") private volatile java.lang.Object googleDemarcId_ = ""; /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return Whether the googleDemarcId field is set. */ @java.lang.Override public boolean hasGoogleDemarcId() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return The googleDemarcId. */ @java.lang.Override public java.lang.String getGoogleDemarcId() { java.lang.Object ref = googleDemarcId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); googleDemarcId_ = s; return s; } } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return The bytes for googleDemarcId. */ @java.lang.Override public com.google.protobuf.ByteString getGoogleDemarcIdBytes() { java.lang.Object ref = googleDemarcId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); googleDemarcId_ = 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, 28771859, customerDemarcId_); } if (((bitField0_ & 0x00000002) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 262014711, googleCircuitId_); } if (((bitField0_ & 0x00000004) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 448196270, googleDemarcId_); } 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(28771859, customerDemarcId_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(262014711, googleCircuitId_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(448196270, googleDemarcId_); } 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.InterconnectCircuitInfo)) { return super.equals(obj); } com.google.cloud.compute.v1.InterconnectCircuitInfo other = (com.google.cloud.compute.v1.InterconnectCircuitInfo) obj; if (hasCustomerDemarcId() != other.hasCustomerDemarcId()) return false; if (hasCustomerDemarcId()) { if (!getCustomerDemarcId().equals(other.getCustomerDemarcId())) return false; } if (hasGoogleCircuitId() != other.hasGoogleCircuitId()) return false; if (hasGoogleCircuitId()) { if (!getGoogleCircuitId().equals(other.getGoogleCircuitId())) return false; } if (hasGoogleDemarcId() != other.hasGoogleDemarcId()) return false; if (hasGoogleDemarcId()) { if (!getGoogleDemarcId().equals(other.getGoogleDemarcId())) 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 (hasCustomerDemarcId()) { hash = (37 * hash) + CUSTOMER_DEMARC_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerDemarcId().hashCode(); } if (hasGoogleCircuitId()) { hash = (37 * hash) + GOOGLE_CIRCUIT_ID_FIELD_NUMBER; hash = (53 * hash) + getGoogleCircuitId().hashCode(); } if (hasGoogleDemarcId()) { hash = (37 * hash) + GOOGLE_DEMARC_ID_FIELD_NUMBER; hash = (53 * hash) + getGoogleDemarcId().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.InterconnectCircuitInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo 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.InterconnectCircuitInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo 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.InterconnectCircuitInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo 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.InterconnectCircuitInfo parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo 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.InterconnectCircuitInfo parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo 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.InterconnectCircuitInfo 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.InterconnectCircuitInfo 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.InterconnectCircuitInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Describes a single physical circuit between the Customer and Google. CircuitInfo objects are created by Google, so all fields are output only. * </pre> * * Protobuf type {@code google.cloud.compute.v1.InterconnectCircuitInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.InterconnectCircuitInfo) com.google.cloud.compute.v1.InterconnectCircuitInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InterconnectCircuitInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_InterconnectCircuitInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.InterconnectCircuitInfo.class, com.google.cloud.compute.v1.InterconnectCircuitInfo.Builder.class); } // Construct using com.google.cloud.compute.v1.InterconnectCircuitInfo.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; customerDemarcId_ = ""; googleCircuitId_ = ""; googleDemarcId_ = ""; 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_InterconnectCircuitInfo_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.InterconnectCircuitInfo getDefaultInstanceForType() { return com.google.cloud.compute.v1.InterconnectCircuitInfo.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.InterconnectCircuitInfo build() { com.google.cloud.compute.v1.InterconnectCircuitInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.InterconnectCircuitInfo buildPartial() { com.google.cloud.compute.v1.InterconnectCircuitInfo result = new com.google.cloud.compute.v1.InterconnectCircuitInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.InterconnectCircuitInfo result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.customerDemarcId_ = customerDemarcId_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.googleCircuitId_ = googleCircuitId_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.googleDemarcId_ = googleDemarcId_; 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.InterconnectCircuitInfo) { return mergeFrom((com.google.cloud.compute.v1.InterconnectCircuitInfo) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.InterconnectCircuitInfo other) { if (other == com.google.cloud.compute.v1.InterconnectCircuitInfo.getDefaultInstance()) return this; if (other.hasCustomerDemarcId()) { customerDemarcId_ = other.customerDemarcId_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasGoogleCircuitId()) { googleCircuitId_ = other.googleCircuitId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasGoogleDemarcId()) { googleDemarcId_ = other.googleDemarcId_; 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 230174874: { customerDemarcId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 230174874 case 2096117690: { googleCircuitId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 2096117690 case -709397134: { googleDemarcId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case -709397134 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 customerDemarcId_ = ""; /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return Whether the customerDemarcId field is set. */ public boolean hasCustomerDemarcId() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return The customerDemarcId. */ public java.lang.String getCustomerDemarcId() { java.lang.Object ref = customerDemarcId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerDemarcId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return The bytes for customerDemarcId. */ public com.google.protobuf.ByteString getCustomerDemarcIdBytes() { java.lang.Object ref = customerDemarcId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); customerDemarcId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @param value The customerDemarcId to set. * @return This builder for chaining. */ public Builder setCustomerDemarcId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerDemarcId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @return This builder for chaining. */ public Builder clearCustomerDemarcId() { customerDemarcId_ = getDefaultInstance().getCustomerDemarcId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Customer-side demarc ID for this circuit. * </pre> * * <code>optional string customer_demarc_id = 28771859;</code> * * @param value The bytes for customerDemarcId to set. * @return This builder for chaining. */ public Builder setCustomerDemarcIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerDemarcId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object googleCircuitId_ = ""; /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return Whether the googleCircuitId field is set. */ public boolean hasGoogleCircuitId() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return The googleCircuitId. */ public java.lang.String getGoogleCircuitId() { java.lang.Object ref = googleCircuitId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); googleCircuitId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return The bytes for googleCircuitId. */ public com.google.protobuf.ByteString getGoogleCircuitIdBytes() { java.lang.Object ref = googleCircuitId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); googleCircuitId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @param value The googleCircuitId to set. * @return This builder for chaining. */ public Builder setGoogleCircuitId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } googleCircuitId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @return This builder for chaining. */ public Builder clearGoogleCircuitId() { googleCircuitId_ = getDefaultInstance().getGoogleCircuitId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Google-assigned unique ID for this circuit. Assigned at circuit turn-up. * </pre> * * <code>optional string google_circuit_id = 262014711;</code> * * @param value The bytes for googleCircuitId to set. * @return This builder for chaining. */ public Builder setGoogleCircuitIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); googleCircuitId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object googleDemarcId_ = ""; /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return Whether the googleDemarcId field is set. */ public boolean hasGoogleDemarcId() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return The googleDemarcId. */ public java.lang.String getGoogleDemarcId() { java.lang.Object ref = googleDemarcId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); googleDemarcId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return The bytes for googleDemarcId. */ public com.google.protobuf.ByteString getGoogleDemarcIdBytes() { java.lang.Object ref = googleDemarcId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); googleDemarcId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @param value The googleDemarcId to set. * @return This builder for chaining. */ public Builder setGoogleDemarcId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } googleDemarcId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @return This builder for chaining. */ public Builder clearGoogleDemarcId() { googleDemarcId_ = getDefaultInstance().getGoogleDemarcId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Google-side demarc ID for this circuit. Assigned at circuit turn-up and provided by Google to the customer in the LOA. * </pre> * * <code>optional string google_demarc_id = 448196270;</code> * * @param value The bytes for googleDemarcId to set. * @return This builder for chaining. */ public Builder setGoogleDemarcIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); googleDemarcId_ = 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.InterconnectCircuitInfo) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.InterconnectCircuitInfo) private static final com.google.cloud.compute.v1.InterconnectCircuitInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.InterconnectCircuitInfo(); } public static com.google.cloud.compute.v1.InterconnectCircuitInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InterconnectCircuitInfo> PARSER = new com.google.protobuf.AbstractParser<InterconnectCircuitInfo>() { @java.lang.Override public InterconnectCircuitInfo 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<InterconnectCircuitInfo> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InterconnectCircuitInfo> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.InterconnectCircuitInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hadoop
35,259
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ZKFailoverController.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.ha; import java.io.IOException; import java.net.InetSocketAddress; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.ha.ActiveStandbyElector.ActiveNotFoundException; import org.apache.hadoop.ha.ActiveStandbyElector.ActiveStandbyElectorCallback; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo; import org.apache.hadoop.ha.HAServiceProtocol.RequestSource; import org.apache.hadoop.security.ProviderUtils; import org.apache.hadoop.util.ZKUtil; import org.apache.hadoop.util.ZKUtil.ZKAuthInfo; import org.apache.hadoop.ha.HealthMonitor.State; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.PolicyProvider; import org.apache.hadoop.util.StringUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.hadoop.util.ToolRunner; import org.apache.zookeeper.data.ACL; import org.apache.hadoop.classification.VisibleForTesting; import org.apache.hadoop.util.Preconditions; import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.security.SecurityUtil.TruststoreKeystore; @InterfaceAudience.LimitedPrivate("HDFS") public abstract class ZKFailoverController { static final Logger LOG = LoggerFactory.getLogger(ZKFailoverController.class); public static final String ZK_QUORUM_KEY = "ha.zookeeper.quorum"; private static final String ZK_SESSION_TIMEOUT_KEY = "ha.zookeeper.session-timeout.ms"; private static final int ZK_SESSION_TIMEOUT_DEFAULT = 10*1000; private static final String ZK_PARENT_ZNODE_KEY = "ha.zookeeper.parent-znode"; public static final String ZK_ACL_KEY = "ha.zookeeper.acl"; private static final String ZK_ACL_DEFAULT = "world:anyone:rwcda"; public static final String ZK_AUTH_KEY = "ha.zookeeper.auth"; static final String ZK_PARENT_ZNODE_DEFAULT = "/hadoop-ha"; /** * All of the conf keys used by the ZKFC. This is used in order to allow * them to be overridden on a per-nameservice or per-namenode basis. */ protected static final String[] ZKFC_CONF_KEYS = new String[] { ZK_QUORUM_KEY, ZK_SESSION_TIMEOUT_KEY, ZK_PARENT_ZNODE_KEY, ZK_ACL_KEY, ZK_AUTH_KEY }; protected static final String USAGE = "Usage: hdfs zkfc [ -formatZK [-force] [-nonInteractive] ]\n" + "\t-force: formats the znode if the znode exists.\n" + "\t-nonInteractive: formats the znode aborts if the znode exists,\n" + "\tunless -force option is specified."; /** Unable to format the parent znode in ZK */ static final int ERR_CODE_FORMAT_DENIED = 2; /** The parent znode doesn't exist in ZK */ static final int ERR_CODE_NO_PARENT_ZNODE = 3; /** Fencing is not properly configured */ static final int ERR_CODE_NO_FENCER = 4; /** Automatic failover is not enabled */ static final int ERR_CODE_AUTO_FAILOVER_NOT_ENABLED = 5; /** Cannot connect to ZooKeeper */ static final int ERR_CODE_NO_ZK = 6; protected Configuration conf; private String zkQuorum; protected final HAServiceTarget localTarget; private HealthMonitor healthMonitor; private ActiveStandbyElector elector; protected ZKFCRpcServer rpcServer; private State lastHealthState = State.INITIALIZING; private volatile HAServiceState serviceState = HAServiceState.INITIALIZING; /** Set if a fatal error occurs */ private String fatalError = null; /** * A future nanotime before which the ZKFC will not join the election. * This is used during graceful failover. */ private long delayJoiningUntilNanotime = 0; /** Executor on which {@link #scheduleRecheck(long)} schedules events */ private ScheduledExecutorService delayExecutor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("ZKFC Delay timer #%d") .build()); private ActiveAttemptRecord lastActiveAttemptRecord; private Object activeAttemptRecordLock = new Object(); protected ZKFailoverController(Configuration conf, HAServiceTarget localTarget) { this.localTarget = localTarget; this.conf = conf; } protected abstract byte[] targetToData(HAServiceTarget target); protected abstract HAServiceTarget dataToTarget(byte[] data); protected abstract void loginAsFCUser() throws IOException; protected abstract void checkRpcAdminAccess() throws AccessControlException, IOException; protected abstract InetSocketAddress getRpcAddressToBindTo(); protected abstract PolicyProvider getPolicyProvider(); protected abstract List<HAServiceTarget> getAllOtherNodes(); protected abstract boolean isSSLEnabled(); /** * Return the name of a znode inside the configured parent znode in which * the ZKFC will do all of its work. This is so that multiple federated * nameservices can run on the same ZK quorum without having to manually * configure them to separate subdirectories. * * @return ScopeInsideParentNode. */ protected abstract String getScopeInsideParentNode(); public HAServiceTarget getLocalTarget() { return localTarget; } @VisibleForTesting public HAServiceState getServiceState() { return serviceState; } public int run(final String[] args) throws Exception { if (!localTarget.isAutoFailoverEnabled()) { LOG.error("Automatic failover is not enabled for " + localTarget + "." + " Please ensure that automatic failover is enabled in the " + "configuration before running the ZK failover controller."); return ERR_CODE_AUTO_FAILOVER_NOT_ENABLED; } loginAsFCUser(); try { return SecurityUtil.doAsLoginUserOrFatal(new PrivilegedAction<Integer>() { @Override public Integer run() { try { return doRun(args); } catch (Exception t) { throw new RuntimeException(t); } finally { if (elector != null) { elector.terminateConnection(); } } } }); } catch (RuntimeException rte) { throw (Exception)rte.getCause(); } } private int doRun(String[] args) throws Exception { try { initZK(); } catch (KeeperException ke) { LOG.error("Unable to start failover controller. Unable to connect " + "to ZooKeeper quorum at " + zkQuorum + ". Please check the " + "configured value for " + ZK_QUORUM_KEY + " and ensure that " + "ZooKeeper is running.", ke); return ERR_CODE_NO_ZK; } try { if (args.length > 0) { if ("-formatZK".equals(args[0])) { boolean force = false; boolean interactive = true; for (int i = 1; i < args.length; i++) { if ("-force".equals(args[i])) { force = true; } else if ("-nonInteractive".equals(args[i])) { interactive = false; } else { badArg(args[i]); } } return formatZK(force, interactive); } else { badArg(args[0]); } } } catch (Exception e){ LOG.error("The failover controller encounters runtime error", e); throw e; } if (!elector.parentZNodeExists()) { LOG.error("Unable to start failover controller. " + "Parent znode does not exist.\n" + "Run with -formatZK flag to initialize ZooKeeper."); return ERR_CODE_NO_PARENT_ZNODE; } try { localTarget.checkFencingConfigured(); } catch (BadFencingConfigurationException e) { LOG.error("Fencing is not configured for " + localTarget + ".\n" + "You must configure a fencing method before using automatic " + "failover.", e); return ERR_CODE_NO_FENCER; } try { initRPC(); initHM(); startRPC(); mainLoop(); } catch (Exception e) { LOG.error("The failover controller encounters runtime error: ", e); throw e; } finally { rpcServer.stopAndJoin(); elector.quitElection(true); if (healthMonitor != null) { healthMonitor.shutdown(); healthMonitor.join(); } } return 0; } private void badArg(String arg) { printUsage(); throw new HadoopIllegalArgumentException( "Bad argument: " + arg); } private void printUsage() { System.err.println(USAGE + "\n"); } private int formatZK(boolean force, boolean interactive) throws IOException, InterruptedException, KeeperException { if (elector.parentZNodeExists()) { if (!force && (!interactive || !confirmFormat())) { return ERR_CODE_FORMAT_DENIED; } try { elector.clearParentZNode(); } catch (IOException e) { LOG.error("Unable to clear zk parent znode", e); return 1; } } elector.ensureParentZNode(); return 0; } private boolean confirmFormat() { String parentZnode = getParentZnode(); System.err.println( "===============================================\n" + "The configured parent znode " + parentZnode + " already exists.\n" + "Are you sure you want to clear all failover information from\n" + "ZooKeeper?\n" + "WARNING: Before proceeding, ensure that all HDFS services and\n" + "failover controllers are stopped!\n" + "==============================================="); try { return ToolRunner.confirmPrompt("Proceed formatting " + parentZnode + "?"); } catch (IOException e) { LOG.debug("Failed to confirm", e); return false; } } // ------------------------------------------ // Begin actual guts of failover controller // ------------------------------------------ private void initHM() { healthMonitor = new HealthMonitor(conf, localTarget); healthMonitor.addCallback(new HealthCallbacks()); healthMonitor.addServiceStateCallback(new ServiceStateCallBacks()); healthMonitor.start(); } protected void initRPC() throws IOException { InetSocketAddress bindAddr = getRpcAddressToBindTo(); LOG.info("ZKFC RpcServer binding to {}", bindAddr); rpcServer = new ZKFCRpcServer(conf, bindAddr, this, getPolicyProvider()); } protected void startRPC() throws IOException { rpcServer.start(); } private void initZK() throws HadoopIllegalArgumentException, IOException, KeeperException { zkQuorum = conf.get(ZK_QUORUM_KEY); int zkTimeout = conf.getInt(ZK_SESSION_TIMEOUT_KEY, ZK_SESSION_TIMEOUT_DEFAULT); // Parse ACLs from configuration. String zkAclConf = conf.get(ZK_ACL_KEY, ZK_ACL_DEFAULT); zkAclConf = ZKUtil.resolveConfIndirection(zkAclConf); List<ACL> zkAcls = ZKUtil.parseACLs(zkAclConf); if (zkAcls.isEmpty()) { zkAcls = Ids.CREATOR_ALL_ACL; } // Parse authentication from configuration. Exclude any Credential providers // using the hdfs scheme to avoid a circular dependency. As HDFS is likely // not started when ZKFC is started, we cannot read the credentials from it. Configuration c = conf; try { c = ProviderUtils.excludeIncompatibleCredentialProviders( conf, FileSystem.getFileSystemClass("hdfs", conf)); } catch (UnsupportedFileSystemException e) { // Should not happen in a real cluster, as the hdfs FS will always be // present. Inside tests, the hdfs filesystem will not be present LOG.debug("No filesystem found for the hdfs scheme", e); } List<ZKAuthInfo> zkAuths = SecurityUtil.getZKAuthInfos(c, ZK_AUTH_KEY); // Sanity check configuration. Preconditions.checkArgument(zkQuorum != null, "Missing required configuration '%s' for ZooKeeper quorum", ZK_QUORUM_KEY); Preconditions.checkArgument(zkTimeout > 0, "Invalid ZK session timeout %s", zkTimeout); int maxRetryNum = conf.getInt( CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_KEY, CommonConfigurationKeys.HA_FC_ELECTOR_ZK_OP_RETRIES_DEFAULT); TruststoreKeystore truststoreKeystore = isSSLEnabled() ? new TruststoreKeystore(conf) : null; elector = new ActiveStandbyElector(zkQuorum, zkTimeout, getParentZnode(), zkAcls, zkAuths, new ElectorCallbacks(), maxRetryNum, truststoreKeystore); } private String getParentZnode() { String znode = conf.get(ZK_PARENT_ZNODE_KEY, ZK_PARENT_ZNODE_DEFAULT); if (!znode.endsWith("/")) { znode += "/"; } return znode + getScopeInsideParentNode(); } private synchronized void mainLoop() throws InterruptedException { while (fatalError == null) { wait(); } assert fatalError != null; // only get here on fatal throw new RuntimeException( "ZK Failover Controller failed: " + fatalError); } private synchronized void fatalError(String err) { LOG.error("Fatal error occurred:" + err); fatalError = err; notifyAll(); } private synchronized void becomeActive() throws ServiceFailedException { LOG.info("Trying to make " + localTarget + " active..."); try { HAServiceProtocolHelper.transitionToActive(localTarget.getProxy( conf, FailoverController.getRpcTimeoutToNewActive(conf)), createReqInfo()); String msg = "Successfully transitioned " + localTarget + " to active state"; LOG.info(msg); serviceState = HAServiceState.ACTIVE; recordActiveAttempt(new ActiveAttemptRecord(true, msg)); } catch (Throwable t) { String msg = "Couldn't make " + localTarget + " active"; LOG.error(msg, t); recordActiveAttempt(new ActiveAttemptRecord(false, msg + "\n" + StringUtils.stringifyException(t))); if (t instanceof ServiceFailedException) { throw (ServiceFailedException)t; } else { throw new ServiceFailedException("Couldn't transition to active", t); } /* * TODO: * we need to make sure that if we get fenced and then quickly restarted, * none of these calls will retry across the restart boundary * perhaps the solution is that, whenever the nn starts, it gets a unique * ID, and when we start becoming active, we record it, and then any future * calls use the same ID */ } } /** * Store the results of the last attempt to become active. * This is used so that, during manually initiated failover, * we can report back the results of the attempt to become active * to the initiator of the failover. */ private void recordActiveAttempt( ActiveAttemptRecord record) { synchronized (activeAttemptRecordLock) { lastActiveAttemptRecord = record; activeAttemptRecordLock.notifyAll(); } } /** * Wait until one of the following events: * <ul> * <li>Another thread publishes the results of an attempt to become active * using {@link #recordActiveAttempt(ActiveAttemptRecord)}</li> * <li>The node enters bad health status</li> * <li>The specified timeout elapses</li> * </ul> * * @param timeoutMillis number of millis to wait * @param onlyAfterNanoTime accept attempt records only after a given * timestamp. Use this parameter to ignore the old attempt records from a * previous fail-over attempt. * @return the published record, or null if the timeout elapses or the * service becomes unhealthy * @throws InterruptedException if the thread is interrupted. */ private ActiveAttemptRecord waitForActiveAttempt(int timeoutMillis, long onlyAfterNanoTime) throws InterruptedException { long waitUntil = onlyAfterNanoTime + TimeUnit.NANOSECONDS.convert( timeoutMillis, TimeUnit.MILLISECONDS); do { // periodically check health state, because entering an // unhealthy state could prevent us from ever attempting to // become active. We can detect this and respond to the user // immediately. synchronized (this) { if (lastHealthState != State.SERVICE_HEALTHY) { // early out if service became unhealthy return null; } } synchronized (activeAttemptRecordLock) { if ((lastActiveAttemptRecord != null && lastActiveAttemptRecord.nanoTime >= onlyAfterNanoTime)) { return lastActiveAttemptRecord; } // Only wait 1sec so that we periodically recheck the health state // above. activeAttemptRecordLock.wait(1000); } } while (System.nanoTime() < waitUntil); // Timeout elapsed. LOG.warn(timeoutMillis + "ms timeout elapsed waiting for an attempt " + "to become active"); return null; } private StateChangeRequestInfo createReqInfo() { return new StateChangeRequestInfo(RequestSource.REQUEST_BY_ZKFC); } private synchronized void becomeStandby() { LOG.info("ZK Election indicated that " + localTarget + " should become standby"); try { int timeout = FailoverController.getGracefulFenceTimeout(conf); localTarget.getProxy(conf, timeout).transitionToStandby(createReqInfo()); LOG.info("Successfully transitioned " + localTarget + " to standby state"); } catch (Exception e) { LOG.error("Couldn't transition " + localTarget + " to standby state", e); // TODO handle this. It's a likely case since we probably got fenced // at the same time. } serviceState = HAServiceState.STANDBY; } private synchronized void fenceOldActive(byte[] data) { HAServiceTarget target = dataToTarget(data); try { doFence(target); } catch (Throwable t) { recordActiveAttempt(new ActiveAttemptRecord(false, "Unable to fence old active: " + StringUtils.stringifyException(t))); throw t; } } private void doFence(HAServiceTarget target) { LOG.info("Should fence: " + target); boolean gracefulWorked = new FailoverController(conf, RequestSource.REQUEST_BY_ZKFC).tryGracefulFence(target); if (gracefulWorked) { // It's possible that it's in standby but just about to go into active, // no? Is there some race here? LOG.info("Successfully transitioned " + target + " to standby " + "state without fencing"); return; } try { target.checkFencingConfigured(); } catch (BadFencingConfigurationException e) { LOG.error("Couldn't fence old active " + target, e); recordActiveAttempt(new ActiveAttemptRecord(false, "Unable to fence old active")); throw new RuntimeException(e); } if (!target.getFencer().fence(target)) { throw new RuntimeException("Unable to fence " + target); } } /** * Request from graceful failover to cede active role. Causes * this ZKFC to transition its local node to standby, then quit * the election for the specified period of time, after which it * will rejoin iff it is healthy. */ void cedeActive(final int millisToCede) throws AccessControlException, ServiceFailedException, IOException { try { UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doCedeActive(millisToCede); return null; } }); } catch (InterruptedException e) { throw new IOException(e); } } private void doCedeActive(int millisToCede) throws AccessControlException, ServiceFailedException, IOException { int timeout = FailoverController.getGracefulFenceTimeout(conf); // Lock elector to maintain lock ordering of elector -> ZKFC synchronized (elector) { synchronized (this) { if (millisToCede <= 0) { delayJoiningUntilNanotime = 0; recheckElectability(); return; } LOG.info("Requested by " + UserGroupInformation.getCurrentUser() + " at " + Server.getRemoteAddress() + " to cede active role."); boolean needFence = false; try { localTarget.getProxy(conf, timeout).transitionToStandby(createReqInfo()); LOG.info("Successfully ensured local node is in standby mode"); } catch (IOException ioe) { LOG.warn("Unable to transition local node to standby: " + ioe.getLocalizedMessage()); LOG.warn("Quitting election but indicating that fencing is " + "necessary"); needFence = true; } delayJoiningUntilNanotime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millisToCede); elector.quitElection(needFence); serviceState = HAServiceState.INITIALIZING; } } recheckElectability(); } /** * Coordinate a graceful failover to this node. * @throws ServiceFailedException if the node fails to become active * @throws IOException some other error occurs */ void gracefulFailoverToYou() throws ServiceFailedException, IOException { try { UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doGracefulFailover(); return null; } }); } catch (InterruptedException e) { throw new IOException(e); } } /** * Coordinate a graceful failover. This proceeds in several phases: * 1) Pre-flight checks: ensure that the local node is healthy, and * thus a candidate for failover. * 2a) Determine the current active node. If it is the local node, no * need to failover - return success. * 2b) Get the other nodes * 3a) Ask the other nodes to yield from election for a number of seconds * 3b) Ask the active node to yield from the election for a number of seconds. * 4) Allow the normal election path to run in other threads. Wait until * we either become unhealthy or we see an election attempt recorded by * the normal code path. * 5) Allow the old active to rejoin the election, so a future * failback is possible. */ private void doGracefulFailover() throws ServiceFailedException, IOException, InterruptedException { int timeout = FailoverController.getGracefulFenceTimeout(conf) * 2; Preconditions.checkArgument(timeout >= 0, "timeout should be non-negative."); // Phase 1: pre-flight checks checkEligibleForFailover(); // Phase 2: determine old/current active node. Check that we're not // ourselves active, etc. HAServiceTarget oldActive = getCurrentActive(); if (oldActive == null) { // No node is currently active. So, if we aren't already // active ourselves by means of a normal election, then there's // probably something preventing us from becoming active. throw new ServiceFailedException( "No other node is currently active."); } if (oldActive.getAddress().equals(localTarget.getAddress())) { LOG.info("Local node " + localTarget + " is already active. " + "No need to failover. Returning success."); return; } // Phase 2b: get the other nodes List<HAServiceTarget> otherNodes = getAllOtherNodes(); List<ZKFCProtocol> otherZkfcs = new ArrayList<ZKFCProtocol>(otherNodes.size()); // Phase 3: ask the other nodes to yield from the election. long st = System.nanoTime(); HAServiceTarget activeNode = null; for (HAServiceTarget remote : otherNodes) { // same location, same node - may not always be == equality if (remote.getAddress().equals(oldActive.getAddress())) { activeNode = remote; continue; } otherZkfcs.add(cedeRemoteActive(remote, timeout)); } assert activeNode != null : "Active node does not match any known remote node"; // Phase 3b: ask the old active to yield otherZkfcs.add(cedeRemoteActive(activeNode, timeout)); // Phase 4: wait for the normal election to make the local node // active. ActiveAttemptRecord attempt = waitForActiveAttempt(timeout + 60000, st); if (attempt == null) { // We didn't even make an attempt to become active. synchronized(this) { if (lastHealthState != State.SERVICE_HEALTHY) { throw new ServiceFailedException("Unable to become active. " + "Service became unhealthy while trying to failover."); } } throw new ServiceFailedException("Unable to become active. " + "Local node did not get an opportunity to do so from ZooKeeper, " + "or the local node took too long to transition to active."); } // Phase 5. At this point, we made some attempt to become active. So we // can tell the old active to rejoin if it wants. This allows a quick // fail-back if we immediately crash. for (ZKFCProtocol zkfc : otherZkfcs) { zkfc.cedeActive(-1); } if (attempt.succeeded) { LOG.info("Successfully became active. " + attempt.status); } else { // Propagate failure String msg = "Failed to become active. " + attempt.status; throw new ServiceFailedException(msg); } } /** * Ask the remote zkfc to cede its active status and wait for the specified * timeout before attempting to claim leader status. * @param remote node to ask * @param timeout amount of time to cede * @return the {@link ZKFCProtocol} used to talk to the ndoe * @throws IOException */ private ZKFCProtocol cedeRemoteActive(HAServiceTarget remote, int timeout) throws IOException { LOG.info("Asking " + remote + " to cede its active state for " + timeout + "ms"); ZKFCProtocol oldZkfc = remote.getZKFCProxy(conf, timeout); oldZkfc.cedeActive(timeout); return oldZkfc; } /** * If the local node is an observer or is unhealthy it * is not eligible for graceful failover. * @throws ServiceFailedException if the node is an observer or unhealthy */ private synchronized void checkEligibleForFailover() throws ServiceFailedException { // Check health if (this.getLastHealthState() != State.SERVICE_HEALTHY) { throw new ServiceFailedException( localTarget + " is not currently healthy. " + "Cannot be failover target"); } if (serviceState == HAServiceState.OBSERVER) { throw new ServiceFailedException( localTarget + " is in observer state. " + "Cannot be failover target"); } } /** * @return an {@link HAServiceTarget} for the current active node * in the cluster, or null if no node is active. * @throws IOException if a ZK-related issue occurs * @throws InterruptedException if thread is interrupted */ private HAServiceTarget getCurrentActive() throws IOException, InterruptedException { synchronized (elector) { synchronized (this) { byte[] activeData; try { activeData = elector.getActiveData(); } catch (ActiveNotFoundException e) { return null; } catch (KeeperException ke) { throw new IOException( "Unexpected ZooKeeper issue fetching active node info", ke); } HAServiceTarget oldActive = dataToTarget(activeData); return oldActive; } } } /** * Check the current state of the service, and join the election * if it should be in the election. */ private void recheckElectability() { // Maintain lock ordering of elector -> ZKFC synchronized (elector) { synchronized (this) { boolean healthy = lastHealthState == State.SERVICE_HEALTHY; long remainingDelay = delayJoiningUntilNanotime - System.nanoTime(); if (remainingDelay > 0) { if (healthy) { LOG.info("Would have joined master election, but this node is " + "prohibited from doing so for " + TimeUnit.NANOSECONDS.toMillis(remainingDelay) + " more ms"); } scheduleRecheck(remainingDelay); return; } switch (lastHealthState) { case SERVICE_HEALTHY: if(serviceState != HAServiceState.OBSERVER) { elector.joinElection(targetToData(localTarget)); } if (quitElectionOnBadState) { quitElectionOnBadState = false; } break; case INITIALIZING: LOG.info("Ensuring that " + localTarget + " does not " + "participate in active master election"); elector.quitElection(false); serviceState = HAServiceState.INITIALIZING; break; case SERVICE_UNHEALTHY: case SERVICE_NOT_RESPONDING: LOG.info("Quitting master election for " + localTarget + " and marking that fencing is necessary"); elector.quitElection(true); serviceState = HAServiceState.INITIALIZING; break; case HEALTH_MONITOR_FAILED: fatalError("Health monitor failed!"); break; default: throw new IllegalArgumentException("Unhandled state:" + lastHealthState); } } } } /** * Schedule a call to {@link #recheckElectability()} in the future. */ private void scheduleRecheck(long whenNanos) { delayExecutor.schedule( new Runnable() { @Override public void run() { try { recheckElectability(); } catch (Throwable t) { fatalError("Failed to recheck electability: " + StringUtils.stringifyException(t)); } } }, whenNanos, TimeUnit.NANOSECONDS); } int serviceStateMismatchCount = 0; boolean quitElectionOnBadState = false; void verifyChangedServiceState(HAServiceState changedState) { synchronized (elector) { synchronized (this) { if (serviceState == HAServiceState.INITIALIZING) { if (quitElectionOnBadState) { LOG.debug("rechecking for electability from bad state"); recheckElectability(); } return; } if (changedState == HAServiceState.OBSERVER) { elector.quitElection(true); serviceState = HAServiceState.OBSERVER; return; } if (changedState == serviceState) { serviceStateMismatchCount = 0; return; } if (serviceStateMismatchCount == 0) { // recheck one more time. As this might be due to parallel transition. serviceStateMismatchCount++; return; } // quit the election as the expected state and reported state // mismatches. LOG.error("Local service " + localTarget + " has changed the serviceState to " + changedState + ". Expected was " + serviceState + ". Quitting election marking fencing necessary."); delayJoiningUntilNanotime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(1000); elector.quitElection(true); quitElectionOnBadState = true; serviceStateMismatchCount = 0; serviceState = HAServiceState.INITIALIZING; } } } /** * @return the last health state passed to the FC * by the HealthMonitor. */ protected synchronized State getLastHealthState() { return lastHealthState; } protected synchronized void setLastHealthState(HealthMonitor.State newState) { LOG.info("Local service " + localTarget + " entered state: " + newState); lastHealthState = newState; } @VisibleForTesting public ActiveStandbyElector getElectorForTests() { return elector; } @VisibleForTesting ZKFCRpcServer getRpcServerForTests() { return rpcServer; } /** * Callbacks from elector */ class ElectorCallbacks implements ActiveStandbyElectorCallback { @Override public void becomeActive() throws ServiceFailedException { ZKFailoverController.this.becomeActive(); } @Override public void becomeStandby() { ZKFailoverController.this.becomeStandby(); } @Override public void enterNeutralMode() { } @Override public void notifyFatalError(String errorMessage) { fatalError(errorMessage); } @Override public void fenceOldActive(byte[] data) { ZKFailoverController.this.fenceOldActive(data); } @Override public String toString() { synchronized (ZKFailoverController.this) { return "Elector callbacks for " + localTarget; } } } /** * Callbacks from HealthMonitor */ class HealthCallbacks implements HealthMonitor.Callback { @Override public void enteredState(HealthMonitor.State newState) { setLastHealthState(newState); recheckElectability(); } } /** * Callbacks for HAServiceStatus */ class ServiceStateCallBacks implements HealthMonitor.ServiceStateCallback { @Override public void reportServiceStatus(HAServiceStatus status) { verifyChangedServiceState(status.getState()); } } private static class ActiveAttemptRecord { private final boolean succeeded; private final String status; private final long nanoTime; public ActiveAttemptRecord(boolean succeeded, String status) { this.succeeded = succeeded; this.status = status; this.nanoTime = System.nanoTime(); } } }
google/ExoPlayer
35,373
library/common/src/main/java/com/google/android/exoplayer2/ForwardingPlayer.java
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2; import android.os.Looper; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import androidx.annotation.Nullable; import com.google.android.exoplayer2.audio.AudioAttributes; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.text.Cue; import com.google.android.exoplayer2.text.CueGroup; import com.google.android.exoplayer2.trackselection.TrackSelectionParameters; import com.google.android.exoplayer2.util.Size; import com.google.android.exoplayer2.video.VideoSize; import java.util.List; /** * A {@link Player} that forwards method calls to another {@link Player}. Applications can use this * class to suppress or modify specific operations, by overriding the respective methods. * * @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which * contains the same ExoPlayer code). See <a * href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the * migration guide</a> for more details, including a script to help with the migration. */ @Deprecated public class ForwardingPlayer implements Player { private final Player player; /** Creates a new instance that forwards all operations to {@code player}. */ public ForwardingPlayer(Player player) { this.player = player; } /** Calls {@link Player#getApplicationLooper()} on the delegate and returns the result. */ @Override public Looper getApplicationLooper() { return player.getApplicationLooper(); } /** * Calls {@link Player#addListener(Listener)} on the delegate. * * <p>Overrides of this method must <strong>not</strong> directly call {@code * delegate.addListener}. If the override wants to pass the {@link Player.Listener} instance to * the delegate {@link Player}, it must do so by calling {@code super.addListener} instead. This * ensures the correct {@link Player} instance is passed to {@link * Player.Listener#onEvents(Player, Events)} (i.e. this forwarding instance, and not the * underlying {@code delegate} instance). */ @Override public void addListener(Listener listener) { player.addListener(new ForwardingListener(this, listener)); } /** * Calls {@link Player#removeListener(Listener)} on the delegate. * * <p>Overrides of this method must <strong>not</strong> directly call {@code * delegate.removeListener}. If the override wants to pass the {@link Player.Listener} instance to * the delegate {@link Player}, it must do so by calling {@code super.removeListener} instead. */ @Override public void removeListener(Listener listener) { player.removeListener(new ForwardingListener(this, listener)); } /** Calls {@link Player#setMediaItems(List)} on the delegate. */ @Override public void setMediaItems(List<MediaItem> mediaItems) { player.setMediaItems(mediaItems); } /** Calls {@link Player#setMediaItems(List, boolean)} ()} on the delegate. */ @Override public void setMediaItems(List<MediaItem> mediaItems, boolean resetPosition) { player.setMediaItems(mediaItems, resetPosition); } /** Calls {@link Player#setMediaItems(List, int, long)} on the delegate. */ @Override public void setMediaItems(List<MediaItem> mediaItems, int startIndex, long startPositionMs) { player.setMediaItems(mediaItems, startIndex, startPositionMs); } /** Calls {@link Player#setMediaItem(MediaItem)} on the delegate. */ @Override public void setMediaItem(MediaItem mediaItem) { player.setMediaItem(mediaItem); } /** Calls {@link Player#setMediaItem(MediaItem, long)} on the delegate. */ @Override public void setMediaItem(MediaItem mediaItem, long startPositionMs) { player.setMediaItem(mediaItem, startPositionMs); } /** Calls {@link Player#setMediaItem(MediaItem, boolean)} on the delegate. */ @Override public void setMediaItem(MediaItem mediaItem, boolean resetPosition) { player.setMediaItem(mediaItem, resetPosition); } /** Calls {@link Player#addMediaItem(MediaItem)} on the delegate. */ @Override public void addMediaItem(MediaItem mediaItem) { player.addMediaItem(mediaItem); } /** Calls {@link Player#addMediaItem(int, MediaItem)} on the delegate. */ @Override public void addMediaItem(int index, MediaItem mediaItem) { player.addMediaItem(index, mediaItem); } /** Calls {@link Player#addMediaItems(List)} on the delegate. */ @Override public void addMediaItems(List<MediaItem> mediaItems) { player.addMediaItems(mediaItems); } /** Calls {@link Player#addMediaItems(int, List)} on the delegate. */ @Override public void addMediaItems(int index, List<MediaItem> mediaItems) { player.addMediaItems(index, mediaItems); } /** Calls {@link Player#moveMediaItem(int, int)} on the delegate. */ @Override public void moveMediaItem(int currentIndex, int newIndex) { player.moveMediaItem(currentIndex, newIndex); } /** Calls {@link Player#moveMediaItems(int, int, int)} on the delegate. */ @Override public void moveMediaItems(int fromIndex, int toIndex, int newIndex) { player.moveMediaItems(fromIndex, toIndex, newIndex); } /** Calls {@link Player#replaceMediaItem(int, MediaItem)} on the delegate. */ @Override public void replaceMediaItem(int index, MediaItem mediaItem) { player.replaceMediaItem(index, mediaItem); } /** Calls {@link Player#replaceMediaItems(int, int, List)} on the delegate. */ @Override public void replaceMediaItems(int fromIndex, int toIndex, List<MediaItem> mediaItems) { player.replaceMediaItems(fromIndex, toIndex, mediaItems); } /** Calls {@link Player#removeMediaItem(int)} on the delegate. */ @Override public void removeMediaItem(int index) { player.removeMediaItem(index); } /** Calls {@link Player#removeMediaItems(int, int)} on the delegate. */ @Override public void removeMediaItems(int fromIndex, int toIndex) { player.removeMediaItems(fromIndex, toIndex); } /** Calls {@link Player#clearMediaItems()} on the delegate. */ @Override public void clearMediaItems() { player.clearMediaItems(); } /** Calls {@link Player#isCommandAvailable(int)} on the delegate and returns the result. */ @Override public boolean isCommandAvailable(@Command int command) { return player.isCommandAvailable(command); } /** Calls {@link Player#canAdvertiseSession()} on the delegate and returns the result. */ @Override public boolean canAdvertiseSession() { return player.canAdvertiseSession(); } /** Calls {@link Player#getAvailableCommands()} on the delegate and returns the result. */ @Override public Commands getAvailableCommands() { return player.getAvailableCommands(); } /** Calls {@link Player#prepare()} on the delegate. */ @Override public void prepare() { player.prepare(); } /** Calls {@link Player#getPlaybackState()} on the delegate and returns the result. */ @Override public int getPlaybackState() { return player.getPlaybackState(); } /** Calls {@link Player#getPlaybackSuppressionReason()} on the delegate and returns the result. */ @Override public int getPlaybackSuppressionReason() { return player.getPlaybackSuppressionReason(); } /** Calls {@link Player#isPlaying()} on the delegate and returns the result. */ @Override public boolean isPlaying() { return player.isPlaying(); } /** Calls {@link Player#getPlayerError()} on the delegate and returns the result. */ @Nullable @Override public PlaybackException getPlayerError() { return player.getPlayerError(); } /** Calls {@link Player#play()} on the delegate. */ @Override public void play() { player.play(); } /** Calls {@link Player#pause()} on the delegate. */ @Override public void pause() { player.pause(); } /** Calls {@link Player#setPlayWhenReady(boolean)} on the delegate. */ @Override public void setPlayWhenReady(boolean playWhenReady) { player.setPlayWhenReady(playWhenReady); } /** Calls {@link Player#getPlayWhenReady()} on the delegate and returns the result. */ @Override public boolean getPlayWhenReady() { return player.getPlayWhenReady(); } /** Calls {@link Player#setRepeatMode(int)} on the delegate. */ @Override public void setRepeatMode(@RepeatMode int repeatMode) { player.setRepeatMode(repeatMode); } /** Calls {@link Player#getRepeatMode()} on the delegate and returns the result. */ @Override public int getRepeatMode() { return player.getRepeatMode(); } /** Calls {@link Player#setShuffleModeEnabled(boolean)} on the delegate. */ @Override public void setShuffleModeEnabled(boolean shuffleModeEnabled) { player.setShuffleModeEnabled(shuffleModeEnabled); } /** Calls {@link Player#getShuffleModeEnabled()} on the delegate and returns the result. */ @Override public boolean getShuffleModeEnabled() { return player.getShuffleModeEnabled(); } /** Calls {@link Player#isLoading()} on the delegate and returns the result. */ @Override public boolean isLoading() { return player.isLoading(); } /** Calls {@link Player#seekToDefaultPosition()} on the delegate. */ @Override public void seekToDefaultPosition() { player.seekToDefaultPosition(); } /** Calls {@link Player#seekToDefaultPosition(int)} on the delegate. */ @Override public void seekToDefaultPosition(int mediaItemIndex) { player.seekToDefaultPosition(mediaItemIndex); } /** Calls {@link Player#seekTo(long)} on the delegate. */ @Override public void seekTo(long positionMs) { player.seekTo(positionMs); } /** Calls {@link Player#seekTo(int, long)} on the delegate. */ @Override public void seekTo(int mediaItemIndex, long positionMs) { player.seekTo(mediaItemIndex, positionMs); } /** Calls {@link Player#getSeekBackIncrement()} on the delegate and returns the result. */ @Override public long getSeekBackIncrement() { return player.getSeekBackIncrement(); } /** Calls {@link Player#seekBack()} on the delegate. */ @Override public void seekBack() { player.seekBack(); } /** Calls {@link Player#getSeekForwardIncrement()} on the delegate and returns the result. */ @Override public long getSeekForwardIncrement() { return player.getSeekForwardIncrement(); } /** Calls {@link Player#seekForward()} on the delegate. */ @Override public void seekForward() { player.seekForward(); } /** * Calls {@link Player#hasPrevious()} on the delegate and returns the result. * * @deprecated Use {@link #hasPreviousMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean hasPrevious() { return player.hasPrevious(); } /** * Calls {@link Player#hasPreviousWindow()} on the delegate and returns the result. * * @deprecated Use {@link #hasPreviousMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean hasPreviousWindow() { return player.hasPreviousWindow(); } /** Calls {@link Player#hasPreviousMediaItem()} on the delegate and returns the result. */ @Override public boolean hasPreviousMediaItem() { return player.hasPreviousMediaItem(); } /** * Calls {@link Player#previous()} on the delegate. * * @deprecated Use {@link #seekToPreviousMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public void previous() { player.previous(); } /** * Calls {@link Player#seekToPreviousWindow()} on the delegate. * * @deprecated Use {@link #seekToPreviousMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public void seekToPreviousWindow() { player.seekToPreviousWindow(); } /** Calls {@link Player#seekToPreviousMediaItem()} on the delegate. */ @Override public void seekToPreviousMediaItem() { player.seekToPreviousMediaItem(); } /** Calls {@link Player#seekToPrevious()} on the delegate. */ @Override public void seekToPrevious() { player.seekToPrevious(); } /** Calls {@link Player#getMaxSeekToPreviousPosition()} on the delegate and returns the result. */ @Override public long getMaxSeekToPreviousPosition() { return player.getMaxSeekToPreviousPosition(); } /** * Calls {@link Player#hasNext()} on the delegate and returns the result. * * @deprecated Use {@link #hasNextMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean hasNext() { return player.hasNext(); } /** * Calls {@link Player#hasNextWindow()} on the delegate and returns the result. * * @deprecated Use {@link #hasNextMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean hasNextWindow() { return player.hasNextWindow(); } /** Calls {@link Player#hasNextMediaItem()} on the delegate and returns the result. */ @Override public boolean hasNextMediaItem() { return player.hasNextMediaItem(); } /** * Calls {@link Player#next()} on the delegate. * * @deprecated Use {@link #seekToNextMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public void next() { player.next(); } /** * Calls {@link Player#seekToNextWindow()} on the delegate. * * @deprecated Use {@link #seekToNextMediaItem()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public void seekToNextWindow() { player.seekToNextWindow(); } /** Calls {@link Player#seekToNextMediaItem()} on the delegate. */ @Override public void seekToNextMediaItem() { player.seekToNextMediaItem(); } /** Calls {@link Player#seekToNext()} on the delegate. */ @Override public void seekToNext() { player.seekToNext(); } /** Calls {@link Player#setPlaybackParameters(PlaybackParameters)} on the delegate. */ @Override public void setPlaybackParameters(PlaybackParameters playbackParameters) { player.setPlaybackParameters(playbackParameters); } /** Calls {@link Player#setPlaybackSpeed(float)} on the delegate. */ @Override public void setPlaybackSpeed(float speed) { player.setPlaybackSpeed(speed); } /** Calls {@link Player#getPlaybackParameters()} on the delegate and returns the result. */ @Override public PlaybackParameters getPlaybackParameters() { return player.getPlaybackParameters(); } /** Calls {@link Player#stop()} on the delegate. */ @Override public void stop() { player.stop(); } /** Calls {@link Player#release()} on the delegate. */ @Override public void release() { player.release(); } /** Calls {@link Player#getCurrentTracks()} on the delegate and returns the result. */ @Override public Tracks getCurrentTracks() { return player.getCurrentTracks(); } /** Calls {@link Player#getTrackSelectionParameters()} on the delegate and returns the result. */ @Override public TrackSelectionParameters getTrackSelectionParameters() { return player.getTrackSelectionParameters(); } /** Calls {@link Player#setTrackSelectionParameters(TrackSelectionParameters)} on the delegate. */ @Override public void setTrackSelectionParameters(TrackSelectionParameters parameters) { player.setTrackSelectionParameters(parameters); } /** Calls {@link Player#getMediaMetadata()} on the delegate and returns the result. */ @Override public MediaMetadata getMediaMetadata() { return player.getMediaMetadata(); } /** Calls {@link Player#getPlaylistMetadata()} on the delegate and returns the result. */ @Override public MediaMetadata getPlaylistMetadata() { return player.getPlaylistMetadata(); } /** Calls {@link Player#setPlaylistMetadata(MediaMetadata)} on the delegate. */ @Override public void setPlaylistMetadata(MediaMetadata mediaMetadata) { player.setPlaylistMetadata(mediaMetadata); } /** Calls {@link Player#getCurrentManifest()} on the delegate and returns the result. */ @Nullable @Override public Object getCurrentManifest() { return player.getCurrentManifest(); } /** Calls {@link Player#getCurrentTimeline()} on the delegate and returns the result. */ @Override public Timeline getCurrentTimeline() { return player.getCurrentTimeline(); } /** Calls {@link Player#getCurrentPeriodIndex()} on the delegate and returns the result. */ @Override public int getCurrentPeriodIndex() { return player.getCurrentPeriodIndex(); } /** * Calls {@link Player#getCurrentWindowIndex()} on the delegate and returns the result. * * @deprecated Use {@link #getCurrentMediaItemIndex()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public int getCurrentWindowIndex() { return player.getCurrentWindowIndex(); } /** Calls {@link Player#getCurrentMediaItemIndex()} on the delegate and returns the result. */ @Override public int getCurrentMediaItemIndex() { return player.getCurrentMediaItemIndex(); } /** * Calls {@link Player#getNextWindowIndex()} on the delegate and returns the result. * * @deprecated Use {@link #getNextMediaItemIndex()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public int getNextWindowIndex() { return player.getNextWindowIndex(); } /** Calls {@link Player#getNextMediaItemIndex()} on the delegate and returns the result. */ @Override public int getNextMediaItemIndex() { return player.getNextMediaItemIndex(); } /** * Calls {@link Player#getPreviousWindowIndex()} on the delegate and returns the result. * * @deprecated Use {@link #getPreviousMediaItemIndex()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public int getPreviousWindowIndex() { return player.getPreviousWindowIndex(); } /** Calls {@link Player#getPreviousMediaItemIndex()} on the delegate and returns the result. */ @Override public int getPreviousMediaItemIndex() { return player.getPreviousMediaItemIndex(); } /** Calls {@link Player#getCurrentMediaItem()} on the delegate and returns the result. */ @Nullable @Override public MediaItem getCurrentMediaItem() { return player.getCurrentMediaItem(); } /** Calls {@link Player#getMediaItemCount()} on the delegate and returns the result. */ @Override public int getMediaItemCount() { return player.getMediaItemCount(); } /** Calls {@link Player#getMediaItemAt(int)} on the delegate and returns the result. */ @Override public MediaItem getMediaItemAt(int index) { return player.getMediaItemAt(index); } /** Calls {@link Player#getDuration()} on the delegate and returns the result. */ @Override public long getDuration() { return player.getDuration(); } /** Calls {@link Player#getCurrentPosition()} on the delegate and returns the result. */ @Override public long getCurrentPosition() { return player.getCurrentPosition(); } /** Calls {@link Player#getBufferedPosition()} on the delegate and returns the result. */ @Override public long getBufferedPosition() { return player.getBufferedPosition(); } /** Calls {@link Player#getBufferedPercentage()} on the delegate and returns the result. */ @Override public int getBufferedPercentage() { return player.getBufferedPercentage(); } /** Calls {@link Player#getTotalBufferedDuration()} on the delegate and returns the result. */ @Override public long getTotalBufferedDuration() { return player.getTotalBufferedDuration(); } /** * Calls {@link Player#isCurrentWindowDynamic()} on the delegate and returns the result. * * @deprecated Use {@link #isCurrentMediaItemDynamic()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean isCurrentWindowDynamic() { return player.isCurrentWindowDynamic(); } /** Calls {@link Player#isCurrentMediaItemDynamic()} on the delegate and returns the result. */ @Override public boolean isCurrentMediaItemDynamic() { return player.isCurrentMediaItemDynamic(); } /** * Calls {@link Player#isCurrentWindowLive()} on the delegate and returns the result. * * @deprecated Use {@link #isCurrentMediaItemLive()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean isCurrentWindowLive() { return player.isCurrentWindowLive(); } /** Calls {@link Player#isCurrentMediaItemLive()} on the delegate and returns the result. */ @Override public boolean isCurrentMediaItemLive() { return player.isCurrentMediaItemLive(); } /** Calls {@link Player#getCurrentLiveOffset()} on the delegate and returns the result. */ @Override public long getCurrentLiveOffset() { return player.getCurrentLiveOffset(); } /** * Calls {@link Player#isCurrentWindowSeekable()} on the delegate and returns the result. * * @deprecated Use {@link #isCurrentMediaItemSeekable()} instead. */ @SuppressWarnings("deprecation") // Forwarding to deprecated method @Deprecated @Override public boolean isCurrentWindowSeekable() { return player.isCurrentWindowSeekable(); } /** Calls {@link Player#isCurrentMediaItemSeekable()} on the delegate and returns the result. */ @Override public boolean isCurrentMediaItemSeekable() { return player.isCurrentMediaItemSeekable(); } /** Calls {@link Player#isPlayingAd()} on the delegate and returns the result. */ @Override public boolean isPlayingAd() { return player.isPlayingAd(); } /** Calls {@link Player#getCurrentAdGroupIndex()} on the delegate and returns the result. */ @Override public int getCurrentAdGroupIndex() { return player.getCurrentAdGroupIndex(); } /** Calls {@link Player#getCurrentAdIndexInAdGroup()} on the delegate and returns the result. */ @Override public int getCurrentAdIndexInAdGroup() { return player.getCurrentAdIndexInAdGroup(); } /** Calls {@link Player#getContentDuration()} on the delegate and returns the result. */ @Override public long getContentDuration() { return player.getContentDuration(); } /** Calls {@link Player#getContentPosition()} on the delegate and returns the result. */ @Override public long getContentPosition() { return player.getContentPosition(); } /** Calls {@link Player#getContentBufferedPosition()} on the delegate and returns the result. */ @Override public long getContentBufferedPosition() { return player.getContentBufferedPosition(); } /** Calls {@link Player#getAudioAttributes()} on the delegate and returns the result. */ @Override public AudioAttributes getAudioAttributes() { return player.getAudioAttributes(); } /** Calls {@link Player#setVolume(float)} on the delegate. */ @Override public void setVolume(float volume) { player.setVolume(volume); } /** Calls {@link Player#getVolume()} on the delegate and returns the result. */ @Override public float getVolume() { return player.getVolume(); } /** Calls {@link Player#getVideoSize()} on the delegate and returns the result. */ @Override public VideoSize getVideoSize() { return player.getVideoSize(); } /** Calls {@link Player#getSurfaceSize()} on the delegate and returns the result. */ @Override public Size getSurfaceSize() { return player.getSurfaceSize(); } /** Calls {@link Player#clearVideoSurface()} on the delegate. */ @Override public void clearVideoSurface() { player.clearVideoSurface(); } /** Calls {@link Player#clearVideoSurface(Surface)} on the delegate. */ @Override public void clearVideoSurface(@Nullable Surface surface) { player.clearVideoSurface(surface); } /** Calls {@link Player#setVideoSurface(Surface)} on the delegate. */ @Override public void setVideoSurface(@Nullable Surface surface) { player.setVideoSurface(surface); } /** Calls {@link Player#setVideoSurfaceHolder(SurfaceHolder)} on the delegate. */ @Override public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { player.setVideoSurfaceHolder(surfaceHolder); } /** Calls {@link Player#clearVideoSurfaceHolder(SurfaceHolder)} on the delegate. */ @Override public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { player.clearVideoSurfaceHolder(surfaceHolder); } /** Calls {@link Player#setVideoSurfaceView(SurfaceView)} on the delegate. */ @Override public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) { player.setVideoSurfaceView(surfaceView); } /** Calls {@link Player#clearVideoSurfaceView(SurfaceView)} on the delegate. */ @Override public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) { player.clearVideoSurfaceView(surfaceView); } /** Calls {@link Player#setVideoTextureView(TextureView)} on the delegate. */ @Override public void setVideoTextureView(@Nullable TextureView textureView) { player.setVideoTextureView(textureView); } /** Calls {@link Player#clearVideoTextureView(TextureView)} on the delegate. */ @Override public void clearVideoTextureView(@Nullable TextureView textureView) { player.clearVideoTextureView(textureView); } /** Calls {@link Player#getCurrentCues()} on the delegate and returns the result. */ @Override public CueGroup getCurrentCues() { return player.getCurrentCues(); } /** Calls {@link Player#getDeviceInfo()} on the delegate and returns the result. */ @Override public DeviceInfo getDeviceInfo() { return player.getDeviceInfo(); } /** Calls {@link Player#getDeviceVolume()} on the delegate and returns the result. */ @Override public int getDeviceVolume() { return player.getDeviceVolume(); } /** Calls {@link Player#isDeviceMuted()} on the delegate and returns the result. */ @Override public boolean isDeviceMuted() { return player.isDeviceMuted(); } /** * @deprecated Use {@link #setDeviceVolume(int, int)} instead. */ @Deprecated @Override public void setDeviceVolume(int volume) { player.setDeviceVolume(volume); } /** Calls {@link Player#setDeviceVolume(int, int)} on the delegate. */ @Override public void setDeviceVolume(int volume, @C.VolumeFlags int flags) { player.setDeviceVolume(volume, flags); } /** * @deprecated Use {@link #increaseDeviceVolume(int)} instead. */ @Deprecated @Override public void increaseDeviceVolume() { player.increaseDeviceVolume(); } /** Calls {@link Player#increaseDeviceVolume(int)} on the delegate. */ @Override public void increaseDeviceVolume(@C.VolumeFlags int flags) { player.increaseDeviceVolume(flags); } /** * @deprecated Use {@link #decreaseDeviceVolume(int)} instead. */ @Deprecated @Override public void decreaseDeviceVolume() { player.decreaseDeviceVolume(); } /** Calls {@link Player#decreaseDeviceVolume(int)} on the delegate. */ @Override public void decreaseDeviceVolume(@C.VolumeFlags int flags) { player.decreaseDeviceVolume(flags); } /** * @deprecated Use {@link #setDeviceMuted(boolean, int)} instead. */ @Deprecated @Override public void setDeviceMuted(boolean muted) { player.setDeviceMuted(muted); } /** Calls {@link Player#setDeviceMuted(boolean, int)} on the delegate. */ @Override public void setDeviceMuted(boolean muted, @C.VolumeFlags int flags) { player.setDeviceMuted(muted, flags); } /** Returns the {@link Player} to which operations are forwarded. */ public Player getWrappedPlayer() { return player; } private static final class ForwardingListener implements Listener { private final ForwardingPlayer forwardingPlayer; private final Listener listener; public ForwardingListener(ForwardingPlayer forwardingPlayer, Listener listener) { this.forwardingPlayer = forwardingPlayer; this.listener = listener; } @Override public void onEvents(Player player, Events events) { // Replace player with forwarding player. listener.onEvents(forwardingPlayer, events); } @Override public void onTimelineChanged(Timeline timeline, @TimelineChangeReason int reason) { listener.onTimelineChanged(timeline, reason); } @Override public void onMediaItemTransition( @Nullable MediaItem mediaItem, @MediaItemTransitionReason int reason) { listener.onMediaItemTransition(mediaItem, reason); } @Override public void onTracksChanged(Tracks tracks) { listener.onTracksChanged(tracks); } @Override public void onMediaMetadataChanged(MediaMetadata mediaMetadata) { listener.onMediaMetadataChanged(mediaMetadata); } @Override public void onPlaylistMetadataChanged(MediaMetadata mediaMetadata) { listener.onPlaylistMetadataChanged(mediaMetadata); } @Override public void onIsLoadingChanged(boolean isLoading) { listener.onIsLoadingChanged(isLoading); } @Override @SuppressWarnings("deprecation") public void onLoadingChanged(boolean isLoading) { listener.onIsLoadingChanged(isLoading); } @Override public void onAvailableCommandsChanged(Commands availableCommands) { listener.onAvailableCommandsChanged(availableCommands); } @Override public void onTrackSelectionParametersChanged(TrackSelectionParameters parameters) { listener.onTrackSelectionParametersChanged(parameters); } @Override @SuppressWarnings("deprecation") public void onPlayerStateChanged(boolean playWhenReady, @State int playbackState) { listener.onPlayerStateChanged(playWhenReady, playbackState); } @Override public void onPlaybackStateChanged(@State int playbackState) { listener.onPlaybackStateChanged(playbackState); } @Override public void onPlayWhenReadyChanged( boolean playWhenReady, @PlayWhenReadyChangeReason int reason) { listener.onPlayWhenReadyChanged(playWhenReady, reason); } @Override public void onPlaybackSuppressionReasonChanged( @PlayWhenReadyChangeReason int playbackSuppressionReason) { listener.onPlaybackSuppressionReasonChanged(playbackSuppressionReason); } @Override public void onIsPlayingChanged(boolean isPlaying) { listener.onIsPlayingChanged(isPlaying); } @Override public void onRepeatModeChanged(@RepeatMode int repeatMode) { listener.onRepeatModeChanged(repeatMode); } @Override public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) { listener.onShuffleModeEnabledChanged(shuffleModeEnabled); } @Override public void onPlayerError(PlaybackException error) { listener.onPlayerError(error); } @Override public void onPlayerErrorChanged(@Nullable PlaybackException error) { listener.onPlayerErrorChanged(error); } @Override @SuppressWarnings("deprecation") public void onPositionDiscontinuity(@DiscontinuityReason int reason) { listener.onPositionDiscontinuity(reason); } @Override public void onPositionDiscontinuity( PositionInfo oldPosition, PositionInfo newPosition, @DiscontinuityReason int reason) { listener.onPositionDiscontinuity(oldPosition, newPosition, reason); } @Override public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) { listener.onPlaybackParametersChanged(playbackParameters); } @Override public void onSeekBackIncrementChanged(long seekBackIncrementMs) { listener.onSeekBackIncrementChanged(seekBackIncrementMs); } @Override public void onSeekForwardIncrementChanged(long seekForwardIncrementMs) { listener.onSeekForwardIncrementChanged(seekForwardIncrementMs); } @Override public void onMaxSeekToPreviousPositionChanged(long maxSeekToPreviousPositionMs) { listener.onMaxSeekToPreviousPositionChanged(maxSeekToPreviousPositionMs); } @Override public void onVideoSizeChanged(VideoSize videoSize) { listener.onVideoSizeChanged(videoSize); } @Override public void onSurfaceSizeChanged(int width, int height) { listener.onSurfaceSizeChanged(width, height); } @Override public void onRenderedFirstFrame() { listener.onRenderedFirstFrame(); } @Override public void onAudioSessionIdChanged(int audioSessionId) { listener.onAudioSessionIdChanged(audioSessionId); } @Override public void onAudioAttributesChanged(AudioAttributes audioAttributes) { listener.onAudioAttributesChanged(audioAttributes); } @Override public void onVolumeChanged(float volume) { listener.onVolumeChanged(volume); } @Override public void onSkipSilenceEnabledChanged(boolean skipSilenceEnabled) { listener.onSkipSilenceEnabledChanged(skipSilenceEnabled); } @Override public void onCues(List<Cue> cues) { listener.onCues(cues); } @Override public void onCues(CueGroup cueGroup) { listener.onCues(cueGroup); } @Override public void onMetadata(Metadata metadata) { listener.onMetadata(metadata); } @Override public void onDeviceInfoChanged(DeviceInfo deviceInfo) { listener.onDeviceInfoChanged(deviceInfo); } @Override public void onDeviceVolumeChanged(int volume, boolean muted) { listener.onDeviceVolumeChanged(volume, muted); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof ForwardingListener)) { return false; } ForwardingListener that = (ForwardingListener) o; if (!forwardingPlayer.equals(that.forwardingPlayer)) { return false; } return listener.equals(that.listener); } @Override public int hashCode() { int result = forwardingPlayer.hashCode(); result = 31 * result + listener.hashCode(); return result; } } }
apache/hudi
35,347
hudi-spark-datasource/hudi-spark/src/test/java/org/apache/hudi/table/functional/TestSparkNonBlockingConcurrencyControl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hudi.table.functional; import org.apache.hudi.client.SparkRDDWriteClient; import org.apache.hudi.client.WriteClientTestUtils; import org.apache.hudi.client.WriteStatus; import org.apache.hudi.client.transaction.BucketIndexConcurrentFileWritesConflictResolutionStrategy; import org.apache.hudi.client.transaction.lock.InProcessLockProvider; import org.apache.hudi.common.config.HoodieStorageConfig; import org.apache.hudi.common.config.RecordMergeMode; import org.apache.hudi.common.fs.FSUtils; import org.apache.hudi.common.model.HoodieAvroRecord; import org.apache.hudi.common.model.HoodieFailedWritesCleaningPolicy; import org.apache.hudi.common.model.HoodieKey; import org.apache.hudi.common.model.HoodieRecord; import org.apache.hudi.common.model.HoodieTableType; import org.apache.hudi.common.model.HoodieWriteStat; import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload; import org.apache.hudi.common.model.PartialUpdateAvroPayload; import org.apache.hudi.common.model.WriteConcurrencyMode; import org.apache.hudi.common.model.WriteOperationType; import org.apache.hudi.common.table.HoodieTableConfig; import org.apache.hudi.common.table.HoodieTableMetaClient; import org.apache.hudi.common.table.marker.MarkerType; import org.apache.hudi.common.table.timeline.HoodieInstant; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.StringUtils; import org.apache.hudi.common.util.ValidationUtils; import org.apache.hudi.config.HoodieCleanConfig; import org.apache.hudi.config.HoodieCompactionConfig; import org.apache.hudi.config.HoodieIndexConfig; import org.apache.hudi.config.HoodieLayoutConfig; import org.apache.hudi.config.HoodieLockConfig; import org.apache.hudi.config.HoodiePayloadConfig; import org.apache.hudi.config.HoodieWriteConfig; import org.apache.hudi.exception.HoodieWriteConflictException; import org.apache.hudi.index.HoodieIndex; import org.apache.hudi.storage.StoragePath; import org.apache.hudi.table.action.HoodieWriteMetadata; import org.apache.hudi.table.action.commit.SparkBucketIndexPartitioner; import org.apache.hudi.table.storage.HoodieStorageLayout; import org.apache.hudi.testutils.SparkClientFunctionalTestHarness; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.hadoop.fs.Path; import org.apache.parquet.avro.AvroParquetReader; import org.apache.parquet.hadoop.ParquetReader; import org.apache.spark.api.java.JavaRDD; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; import static org.apache.hudi.common.table.HoodieTableConfig.TYPE; import static org.apache.hudi.config.HoodieWriteConfig.ENABLE_SCHEMA_CONFLICT_RESOLUTION; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @Tag("functional") public class TestSparkNonBlockingConcurrencyControl extends SparkClientFunctionalTestHarness { String jsonSchema = "{\n" + " \"type\": \"record\",\n" + " \"name\": \"partialRecord\", \"namespace\":\"org.apache.hudi\",\n" + " \"fields\": [\n" + " {\"name\": \"_hoodie_commit_time\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"_hoodie_commit_seqno\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"_hoodie_record_key\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"_hoodie_partition_path\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"_hoodie_file_name\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"id\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"name\", \"type\": [\"null\", \"string\"]},\n" + " {\"name\": \"age\", \"type\": [\"null\", \"int\"]},\n" + " {\"name\": \"ts\", \"type\": [\"null\", \"long\"]},\n" + " {\"name\": \"part\", \"type\": [\"null\", \"string\"]}\n" + " ]\n" + "}"; private Schema schema; private HoodieTableMetaClient metaClient; @BeforeEach public void setUp() throws Exception { schema = new Schema.Parser().parse(jsonSchema); } @Test public void testNonBlockingConcurrencyControlWithPartialUpdatePayload() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); // start the 1st txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); SparkRDDWriteClient client1 = getHoodieWriteClient(config); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // start the 2nd txn and insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.INSERT); // step to commit the 1st txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 2nd txn client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // There is no base file in partition dir because there is no compaction yet. assertFalse(fileExists(), "No base data files should have been created"); // do compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // result is [(id1,Danny,23,2,par1)] Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,23,2,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } @Test public void testNonBlockingConcurrencyControlWithInflightInstant() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); // start the 1st txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit SparkRDDWriteClient client1 = getHoodieWriteClient(config); List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // start the 2nd txn and insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); writeData(client2, insertTime2, dataset2, false, WriteOperationType.INSERT); // step to commit the 1st txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // schedule compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); // step to commit the 3rd txn, insert record: [id3,Julian,53,4,par1] and commit 3rd txn List<String> dataset3 = Collections.singletonList("id3,Julian,53,4,par1"); String insertTime3 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses3 = writeData(client1, insertTime3, dataset3, false, WriteOperationType.INSERT); client1.commitStats( insertTime3, writeStatuses3.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // do compaction HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // read optimized result is [(id1,Danny,23,1,par1)] // because 2nd commit is in inflight state and // the data files belongs 3rd commit is not included in the last compaction. Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,null,1,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } // Validate that multiple writers will only produce base files for bulk insert @ParameterizedTest @ValueSource(booleans = {true, false}) public void testMultiBaseFile(boolean bulkInsertFirst) throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(true); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); // there should only be a single filegroup, so we will verify that it is consistent String fileID = null; // if there is not a bulk insert first, then we will write to log files for a filegroup // without a base file. Having a base file adds the possibility of small file handling // which we want to ensure doesn't happen. if (bulkInsertFirst) { SparkRDDWriteClient client0 = getHoodieWriteClient(config); List<String> dataset0 = Collections.singletonList("id0,Danny,0,0,par1"); String insertTime0 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses0 = writeData(client0, insertTime0, dataset0, false, WriteOperationType.BULK_INSERT, true); client0.commitStats( insertTime0, writeStatuses0.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); for (WriteStatus status : writeStatuses0) { if (fileID == null) { fileID = status.getFileId(); } else { assertEquals(fileID, status.getFileId()); } assertFalse(FSUtils.isLogFile(new StoragePath(status.getStat().getPath()).getName())); } client0.close(); } SparkRDDWriteClient client1 = getHoodieWriteClient(config); List<String> dataset1 = Collections.singletonList("id1,Danny,22,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT, true); for (WriteStatus status : writeStatuses1) { if (fileID == null) { fileID = status.getFileId(); } else { assertEquals(fileID, status.getFileId()); } assertTrue(FSUtils.isLogFile(new StoragePath(status.getStat().getPath()).getName())); } SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,Danny,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.UPSERT, true); for (WriteStatus status : writeStatuses2) { assertEquals(fileID, status.getFileId()); assertTrue(FSUtils.isLogFile(new StoragePath(status.getStat().getPath()).getName())); } // step to commit the 1st txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 2nd txn client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); client1.close(); client2.close(); metaClient.reloadActiveTimeline(); List<HoodieInstant> instants = metaClient.getActiveTimeline().getInstants(); if (bulkInsertFirst) { assertEquals(3, instants.size()); // check that bulk insert finished before the upsert started assertTrue(Long.parseLong(instants.get(0).getCompletionTime()) < Long.parseLong(instants.get(1).requestedTime())); // check that the upserts overlapped in time assertTrue(Long.parseLong(instants.get(1).getCompletionTime()) > Long.parseLong(instants.get(2).requestedTime())); assertTrue(Long.parseLong(instants.get(2).getCompletionTime()) > Long.parseLong(instants.get(1).requestedTime())); } else { assertEquals(2, instants.size()); // check that the upserts overlapped in time assertTrue(Long.parseLong(instants.get(0).getCompletionTime()) > Long.parseLong(instants.get(1).requestedTime())); assertTrue(Long.parseLong(instants.get(1).getCompletionTime()) > Long.parseLong(instants.get(0).requestedTime())); } } /** * case1: * 1. insert start * 2. insert commit * 3. bulk_insert start * 4. bulk_insert commit * * |------ txn1: insert ------| * |------ txn2: bulk_insert ------| * * both two txn would success to commit */ @Test public void testBulkInsertAndInsertConcurrentCase1() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); // start the 1st txn and insert record: [id1,Danny,null,1,par1], commit the 1st txn SparkRDDWriteClient client1 = getHoodieWriteClient(config); List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); writeData(client1, insertTime1, dataset1, true, WriteOperationType.INSERT); // start the 2nd txn and bulk_insert record: [id1,null,23,2,par1], commit the 2nd txn SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); writeData(client2, insertTime2, dataset2, true, WriteOperationType.BULK_INSERT); // do compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // result is [(id1,Danny,23,2,par1)] Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,23,2,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } /** * case2: * 1. insert start * 2. bulk_insert start * 3. insert commit * 4. bulk_insert commit * * |------ txn1: insert ------| * |------ txn2: bulk_insert ------| * * the txn2 should be fail to commit caused by conflict */ @Test public void testBulkInsertAndInsertConcurrentCase2() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); SparkRDDWriteClient client1 = getHoodieWriteClient(config); // start the 1st txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // start the 2nd txn and bulk insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.BULK_INSERT); // step to commit the 1st txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 2nd txn assertThrows(HoodieWriteConflictException.class, () -> { client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); }); client1.close(); client2.close(); } /** * case3: * 1. bulk_insert start * 2. insert start * 3. insert commit * 4. bulk_insert commit * * |------ txn2: insert ------| * |---------- txn1: bulk_insert ----------| * * the txn2 should be fail to commit caused by conflict */ @Test public void testBulkInsertAndInsertConcurrentCase3() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); SparkRDDWriteClient client1 = getHoodieWriteClient(config); // start the 1st txn and bulk insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.BULK_INSERT); // start the 2nd txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // step to commit the 2nd txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 1st txn assertThrows(HoodieWriteConflictException.class, () -> { client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); }); client1.close(); client2.close(); } /** * case4: * 1. insert start * 2. bulk_insert start * 3. bulk_insert commit * 4. insert commit * * |------------ txn1: insert ------------| * |------ txn2: bulk_insert ------| * * both two txn would success to commit */ @Test public void testBulkInsertAndInsertConcurrentCase4() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); SparkRDDWriteClient client1 = getHoodieWriteClient(config); // start the 1st txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // start the 2nd txn and bulk insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.BULK_INSERT); // step to commit the 2nd txn client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 1st txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // do compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // result is [(id1,Danny,23,2,par1)] Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,23,2,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } /** * case5: * 1. bulk_insert start * 2. insert start * 3. bulk_insert commit * 4. insert commit * * |------ txn2: insert ------| * |---------- txn1: bulk_insert ----------| * * both two txn would success to commit */ @Test public void testBulkInsertAndInsertConcurrentCase5() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); SparkRDDWriteClient client1 = getHoodieWriteClient(config); // start the 1st txn and bulk insert record: [id1,null,23,2,par1], suspend the tx commit SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses2 = writeData(client2, insertTime2, dataset2, false, WriteOperationType.BULK_INSERT); // start the 2nd txn and insert record: [id1,Danny,null,1,par1], suspend the tx commit List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); List<WriteStatus> writeStatuses1 = writeData(client1, insertTime1, dataset1, false, WriteOperationType.INSERT); // step to commit the 1st txn client2.commitStats( insertTime2, writeStatuses2.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // step to commit the 2nd txn client1.commitStats( insertTime1, writeStatuses1.stream().map(WriteStatus::getStat).collect(Collectors.toList()), Option.empty(), metaClient.getCommitActionType()); // do compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // result is [(id1,Danny,23,2,par1)] Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,23,2,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } /** * case6: * 1. bulk_insert start * 2. bulk_insert commit * 3. insert start * 4. insert commit * * |------ txn2: insert ------| * |------ txn1: bulk_insert ------| * * both two txn would success to commit */ @Test public void testBulkInsertAndInsertConcurrentCase6() throws Exception { HoodieWriteConfig config = createHoodieWriteConfig(); metaClient = getHoodieMetaClient(HoodieTableType.MERGE_ON_READ, config.getProps()); // start the 1st txn and bulk insert record: [id1,Danny,null,1,par1], commit the 1st txn SparkRDDWriteClient client1 = getHoodieWriteClient(config); List<String> dataset1 = Collections.singletonList("id1,Danny,,1,par1"); String insertTime1 = WriteClientTestUtils.createNewInstantTime(); writeData(client1, insertTime1, dataset1, true, WriteOperationType.BULK_INSERT); // start the 2nd txn and insert record: [id1,null,23,2,par1], commit the 2nd txn SparkRDDWriteClient client2 = getHoodieWriteClient(config); List<String> dataset2 = Collections.singletonList("id1,,23,2,par1"); String insertTime2 = WriteClientTestUtils.createNewInstantTime(); writeData(client2, insertTime2, dataset2, true, WriteOperationType.INSERT); // do compaction String compactionTime = (String) client1.scheduleCompaction(Option.empty()).get(); HoodieWriteMetadata writeMetadata = client1.compact(compactionTime); client1.commitCompaction(compactionTime, writeMetadata, Option.empty()); assertTrue(metaClient.reloadActiveTimeline().filterCompletedInstants().containsInstant(compactionTime)); // result is [(id1,Danny,23,2,par1)] Map<String, String> result = Collections.singletonMap("par1", "[id1,par1,id1,Danny,23,2,par1]"); checkWrittenData(result, 1); client1.close(); client2.close(); } private HoodieWriteConfig createHoodieWriteConfig() { return createHoodieWriteConfig(false); } private HoodieWriteConfig createHoodieWriteConfig(boolean fullUpdate) { String payloadClassName = PartialUpdateAvroPayload.class.getName(); if (fullUpdate) { payloadClassName = OverwriteWithLatestAvroPayload.class.getName(); } Properties props = getPropertiesForKeyGen(true); props.put(TYPE.key(), HoodieTableType.MERGE_ON_READ.name()); props.put(ENABLE_SCHEMA_CONFLICT_RESOLUTION.key(), "false"); String basePath = basePath(); return HoodieWriteConfig.newBuilder() .withProps(Collections.singletonMap(HoodieTableConfig.ORDERING_FIELDS.key(), "ts")) .forTable("test") .withPath(basePath) .withSchema(jsonSchema) .withParallelism(2, 2) .withRecordMergeMode(RecordMergeMode.CUSTOM) .withPayloadConfig( HoodiePayloadConfig.newBuilder() .withPayloadClass(payloadClassName) .build()) .withCompactionConfig(HoodieCompactionConfig.newBuilder() .withMaxNumDeltaCommitsBeforeCompaction(1).build()) .withStorageConfig(HoodieStorageConfig.newBuilder() .parquetMaxFileSize(1024).build()) .withLayoutConfig(HoodieLayoutConfig.newBuilder() .withLayoutType(HoodieStorageLayout.LayoutType.BUCKET.name()) .withLayoutPartitioner(SparkBucketIndexPartitioner.class.getName()).build()) .withIndexConfig(HoodieIndexConfig.newBuilder() .fromProperties(props) .withIndexType(HoodieIndex.IndexType.BUCKET) .withBucketNum("1") .build()) .withPopulateMetaFields(true) .withCleanConfig(HoodieCleanConfig.newBuilder().withFailedWritesCleaningPolicy(HoodieFailedWritesCleaningPolicy.LAZY).build()) .withWriteConcurrencyMode(WriteConcurrencyMode.NON_BLOCKING_CONCURRENCY_CONTROL) // Timeline-server-based markers are not used for multi-writer tests .withMarkersType(MarkerType.DIRECT.name()) .withLockConfig(HoodieLockConfig.newBuilder() .withLockProvider(InProcessLockProvider.class) .withConflictResolutionStrategy(new BucketIndexConcurrentFileWritesConflictResolutionStrategy()) .build()) .build(); } private void checkWrittenData( Map<String, String> expected, int partitions) throws IOException { File baseFile = tempDir.toFile(); assert baseFile.isDirectory(); FileFilter filter = file -> !file.getName().startsWith("."); File[] partitionDirs = baseFile.listFiles(filter); assertNotNull(partitionDirs); assertThat(partitionDirs.length, is(partitions)); for (File partitionDir : partitionDirs) { File[] dataFiles = partitionDir.listFiles(filter); assertNotNull(dataFiles); File latestDataFile = Arrays.stream(dataFiles) .max(Comparator.comparing(f -> FSUtils.getCommitTime(f.getName()))) .orElse(dataFiles[0]); ParquetReader<GenericRecord> reader = AvroParquetReader .<GenericRecord>builder(new Path(latestDataFile.getAbsolutePath())).build(); List<String> readBuffer = new ArrayList<>(); GenericRecord nextRecord = reader.read(); while (nextRecord != null) { readBuffer.add(filterOutVariables(nextRecord)); nextRecord = reader.read(); } readBuffer.sort(Comparator.naturalOrder()); assertThat(readBuffer.toString(), is(expected.get(partitionDir.getName()))); } } private static String filterOutVariables(GenericRecord genericRecord) { List<String> fields = new ArrayList<>(); fields.add(getFieldValue(genericRecord, "_hoodie_record_key")); fields.add(getFieldValue(genericRecord, "_hoodie_partition_path")); fields.add(getFieldValue(genericRecord, "id")); fields.add(getFieldValue(genericRecord, "name")); fields.add(getFieldValue(genericRecord, "age")); fields.add(genericRecord.get("ts").toString()); fields.add(genericRecord.get("part").toString()); return String.join(",", fields); } private static String getFieldValue(GenericRecord genericRecord, String fieldName) { if (genericRecord.get(fieldName) != null) { return genericRecord.get(fieldName).toString(); } else { return null; } } private boolean fileExists() { List<File> dirsToCheck = new ArrayList<>(); dirsToCheck.add(tempDir.toFile()); while (!dirsToCheck.isEmpty()) { File dir = dirsToCheck.remove(0); for (File file : Objects.requireNonNull(dir.listFiles())) { if (!file.getName().startsWith(".")) { if (file.isDirectory()) { dirsToCheck.add(file); } else { return true; } } } } return false; } private GenericRecord str2GenericRecord(String str) { GenericRecord record = new GenericData.Record(schema); String[] fieldValues = str.split(","); ValidationUtils.checkArgument(fieldValues.length == 5, "Valid record must have 5 fields"); record.put("id", StringUtils.isNullOrEmpty(fieldValues[0]) ? null : fieldValues[0]); record.put("name", StringUtils.isNullOrEmpty(fieldValues[1]) ? null : fieldValues[1]); record.put("age", StringUtils.isNullOrEmpty(fieldValues[2]) ? null : Integer.parseInt(fieldValues[2])); record.put("ts", StringUtils.isNullOrEmpty(fieldValues[3]) ? null : Long.parseLong(fieldValues[3])); record.put("part", StringUtils.isNullOrEmpty(fieldValues[4]) ? null : fieldValues[4]); return record; } private List<HoodieRecord> str2HoodieRecord(List<String> records, boolean fullUpdate) { return records.stream().map(recordStr -> { GenericRecord record = str2GenericRecord(recordStr); OverwriteWithLatestAvroPayload payload; if (fullUpdate) { payload = new OverwriteWithLatestAvroPayload(record, (Long) record.get("ts")); } else { payload = new PartialUpdateAvroPayload(record, (Long) record.get("ts")); } return new HoodieAvroRecord<>(new HoodieKey((String) record.get("id"), (String) record.get("part")), payload); }).collect(Collectors.toList()); } private List<WriteStatus> writeData( SparkRDDWriteClient client, String instant, List<String> records, boolean doCommit, WriteOperationType operationType) { return writeData(client, instant, records, doCommit, operationType, false); } private List<WriteStatus> writeData( SparkRDDWriteClient client, String instant, List<String> records, boolean doCommit, WriteOperationType operationType, boolean fullUpdate) { List<HoodieRecord> recordList = str2HoodieRecord(records, fullUpdate); JavaRDD<HoodieRecord> writeRecords = jsc().parallelize(recordList, 2); metaClient = HoodieTableMetaClient.reload(metaClient); WriteClientTestUtils.startCommitWithTime(client, instant); List<WriteStatus> writeStatuses; switch (operationType) { case INSERT: writeStatuses = client.insert(writeRecords, instant).collect(); break; case UPSERT: writeStatuses = client.upsert(writeRecords, instant).collect(); break; case BULK_INSERT: writeStatuses = client.bulkInsert(writeRecords, instant).collect(); break; default: throw new UnsupportedOperationException(operationType + " is not supported yet in this test!"); } org.apache.hudi.testutils.Assertions.assertNoWriteErrors(writeStatuses); if (doCommit) { List<HoodieWriteStat> writeStats = writeStatuses.stream().map(WriteStatus::getStat).collect(Collectors.toList()); boolean committed = client.commitStats(instant, writeStats, Option.empty(), metaClient.getCommitActionType()); Assertions.assertTrue(committed); } metaClient = HoodieTableMetaClient.reload(metaClient); return writeStatuses; } }
apache/phoenix
35,436
phoenix-core/src/test/java/org/apache/phoenix/schema/ConditionalTTLExpressionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.schema; import static org.apache.phoenix.exception.SQLExceptionCode.AGGREGATE_EXPRESSION_NOT_ALLOWED_IN_CONDITIONAL_TTL; import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_DROP_COL_REFERENCED_IN_CONDITIONAL_TTL; import static org.apache.phoenix.exception.SQLExceptionCode.CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES; import static org.apache.phoenix.schema.LiteralTTLExpression.TTL_EXPRESSION_NOT_DEFINED; import static org.apache.phoenix.schema.PTableType.INDEX; import static org.apache.phoenix.util.TestUtil.retainSingleQuotes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.NavigableSet; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.compile.QueryPlan; import org.apache.phoenix.exception.PhoenixParserException; import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixPreparedStatement; import org.apache.phoenix.query.BaseConnectionlessQueryTest; import org.apache.phoenix.util.EnvironmentEdgeManager; import org.junit.Test; import org.apache.phoenix.thirdparty.com.google.common.collect.Lists; public class ConditionalTTLExpressionTest extends BaseConnectionlessQueryTest { private static void assertConditonTTL(Connection conn, String tableName, String ttlExpr) throws SQLException { TTLExpression expected = new ConditionalTTLExpression(ttlExpr); assertTTL(conn, tableName, expected); } private static void assertTTL(Connection conn, String tableName, TTLExpression expected) throws SQLException { PTable table = conn.unwrap(PhoenixConnection.class).getTable(tableName); assertEquals(expected, table.getTTLExpression()); } private void validateScan(Connection conn, String tableName, String query, String ttl, boolean useIndex, List<String> expectedColsInScan) throws SQLException { PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); PhoenixPreparedStatement pstmt = new PhoenixPreparedStatement(pconn, query); QueryPlan plan = pstmt.optimizeQuery(); if (useIndex) { assertTrue(plan.getTableRef().getTable().getType() == INDEX); } plan.iterator(); // create the iterator to initialize the scan PTable table = plan.getTableRef().getTable(); Scan scan = plan.getContext().getScan(); Map<byte[], NavigableSet<byte[]>> familyMap = scan.getFamilyMap(); assertTrue(!familyMap.isEmpty()); // Conditional TTL is only supported for tables with 1 column family assertTrue(familyMap.size() == 1); byte[] family = scan.getFamilies()[0]; assertNotNull(family); NavigableSet<byte[]> qualifiers = familyMap.get(family); if (expectedColsInScan.isEmpty()) { assertNull(qualifiers); } else { for (String col : expectedColsInScan) { PColumn column = table.getColumnForColumnName(col.toUpperCase()); assertTrue(Bytes.equals(family, column.getFamilyName().getBytes())); assertTrue(qualifiers.contains(column.getColumnQualifierBytes())); } } } @Test public void testBasicExpression() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "k1 > 5 AND col1 < 'zzzzzz'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); String query = String.format("SELECT count(*) from %s where k1 > 3", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1")); } } @Test(expected = TypeMismatchException.class) public void testNotBooleanExpr() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "k1 + 100"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); } } @Test(expected = TypeMismatchException.class) public void testWrongArgumentValue() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "k1 = ''abc''"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); } } @Test(expected = PhoenixParserException.class) public void testParsingError() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "k2 == 23"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); } } @Test public void testMultipleColumnFamilyNotAllowed() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "A.col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "A.col1 = 'expired'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); fail(); } catch (SQLException e) { assertEquals(CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } } @Test public void testSingleNonDefaultColumnFamilyIsAllowed() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "A.col1 varchar, A.col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "col1 = 'expired' AND col2 + 10 > CURRENT_DATE()"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); // create global index String indexName = "I_" + generateUniqueName(); ddl = String.format("create index %s on %s (col2) include(col1)", indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); // create local index indexName = "L_" + generateUniqueName(); ddl = String.format("create local index %s on %s (col2) include(col1)", indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); } } @Test public void testDefaultColumnFamily() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'," + "DEFAULT_COLUMN_FAMILY='CF'"; String ttl = "col1 = 'expired' AND CF.col2 + 10 > CURRENT_DATE()"; String tableName = "T_" + generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); // create view String viewName = "GV_" + generateUniqueName(); ddl = String.format("create view %s (col3 varchar) as select * from %s where k1 = 2", viewName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, viewName, ttl); // create global index String indexName = "I_" + generateUniqueName(); ddl = String.format("create index %s on %s (col2) include(col1)", indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); // create local index indexName = "L_" + generateUniqueName(); ddl = String.format("create local index %s on %s (col2) include(col1)", indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); } } @Test public void testMultipleColumnFamilyNotAllowedOnAlter() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "A.col1 varchar, col2 date constraint pk primary key (k1,k2 desc))"; String ttl = "A.col1 = 'expired'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); String alterDDL = String.format("alter table %s set TTL = '%s'", tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(alterDDL); fail(); } catch (SQLException e) { assertEquals(CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } } @Test public void testMultipleColumnFamilyNotAllowedOnAddColumn() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "A.col1 varchar, A.col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "A.col1 = 'expired'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); // add a new column in a different column family String alterDDL = String.format("alter table %s add col3 varchar", tableName); try { conn.createStatement().execute(alterDDL); fail(); } catch (SQLException e) { assertEquals( CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } alterDDL = String.format("alter table %s add A.col3 varchar", tableName); conn.createStatement().execute(alterDDL); } } @Test public void testMultipleColumnFamilyNotAllowedOnAddColumn2() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "col1 = 'expired'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); // add a new column in a different column family String alterDDL = String.format("alter table %s add A.col3 varchar", tableName); try { conn.createStatement().execute(alterDDL); fail(); } catch (SQLException e) { assertEquals( CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } alterDDL = String.format("alter table %s add col3 varchar", tableName); conn.createStatement().execute(alterDDL); } } @Test public void testMultipleColumnFamilyNotAllowedOnAddColumn3() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'," + "DEFAULT_COLUMN_FAMILY='CF'"; String ttl = "col1 = 'expired' AND CF.col2 + 10 > CURRENT_DATE()"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); // add a new column in a different column family String alterDDL = String.format("alter table %s add A.col3 varchar", tableName); try { conn.createStatement().execute(alterDDL); fail(); } catch (SQLException e) { assertEquals( CANNOT_SET_CONDITIONAL_TTL_ON_TABLE_WITH_MULTIPLE_COLUMN_FAMILIES.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } alterDDL = String.format("alter table %s add col3 varchar", tableName); conn.createStatement().execute(alterDDL); } } @Test public void testDropColumnNotAllowed() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "col1 = 'expired' AND col2 + 30 < CURRENT_DATE()"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); // drop column referenced in TTL expression String alterDDL = String.format("alter table %s drop column col2", tableName); try { conn.createStatement().execute(alterDDL); fail(); } catch (SQLException e) { assertEquals(CANNOT_DROP_COL_REFERENCED_IN_CONDITIONAL_TTL.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } } } @Test public void testAggregateExpressionNotAllowed() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "SUM(k2) > 23"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); fail(); } catch (SQLException e) { assertEquals(AGGREGATE_EXPRESSION_NOT_ALLOWED_IN_CONDITIONAL_TTL.getErrorCode(), e.getErrorCode()); } catch (Exception e) { fail("Unknown exception " + e); } } @Test public void testNullExpression() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String tableName = generateUniqueName(); String ttl = "col1 is NULL AND col2 < CURRENT_DATE() + 30000"; String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); String query = String.format("SELECT count(*) from %s", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1", "col2")); } } @Test public void testBooleanColumn() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "val varchar, expired BOOLEAN constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String tableName = generateUniqueName(); String indexName = "I_" + tableName; String indexTemplate = "create index %s on %s (val) include (expired)"; String ttl = "expired"; String query; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, ttl); conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); query = String.format("SELECT k1, k2 from %s where (k1,k2) IN ((1,2), (3,4))", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("expired")); ddl = String.format(indexTemplate, indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); // validate the scan on index query = String.format("SELECT count(*) from %s", tableName); validateScan(conn, tableName, query, ttl, true, Lists.newArrayList("0:expired")); } } @Test public void testNot() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "expired BOOLEAN constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "NOT expired"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); } } @Test public void testPhoenixRowTimestamp() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String tableName = generateUniqueName(); String ttl = "PHOENIX_ROW_TIMESTAMP() < CURRENT_DATE() - 100"; String ddl = String.format(ddlTemplate, tableName, ttl); String query; try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); query = String.format("select col1 from %s where k1 = 7 AND k2 > 12", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1")); } } @Test public void testBooleanCaseExpression() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, status char(1) constraint pk primary key (k1,k2 desc)) TTL = '%s'"; String ttl = "CASE WHEN status = ''E'' THEN TRUE ELSE FALSE END"; String expectedTTLExpr = "CASE WHEN status = 'E' THEN TRUE ELSE FALSE END"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, ttl); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, expectedTTLExpr); } } @Test public void testCondTTLOnTopLevelView() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null primary key," + "k2 bigint, col1 varchar, status char(1))"; String tableName = generateUniqueName(); String viewName = generateUniqueName(); String viewTemplate = "create view %s (k3 smallint) as select * from %s WHERE k1=7 " + "TTL = '%s'"; String ttl = "k2 = 34 and k3 = -1"; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName); conn.createStatement().execute(ddl); ddl = String.format(viewTemplate, viewName, tableName, ttl); conn.createStatement().execute(ddl); assertTTL(conn, tableName, TTL_EXPRESSION_NOT_DEFINED); assertConditonTTL(conn, viewName, ttl); String query = String.format("select k3 from %s", viewName); validateScan(conn, viewName, query, ttl, false, Lists.newArrayList("k2", "k3")); } } @Test public void testCondTTLOnMultiLevelView() throws SQLException { String ddlTemplate = "create table %s (k1 bigint not null primary key," + "k2 bigint, col1 varchar, status char(1))"; String tableName = generateUniqueName(); String parentView = generateUniqueName(); String childView = generateUniqueName(); String indexName = generateUniqueName(); String parentViewTemplate = "create view %s (k3 smallint) as select * from %s WHERE k1=7"; String childViewTemplate = "create view %s as select * from %s TTL = '%s'"; String indexOnChildTemplate = "create index %s ON %s (k3) include (col1, k2)"; String ttl = "k2 = 34 and k3 = -1"; String ddl = String.format(ddlTemplate, tableName); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); ddl = String.format(parentViewTemplate, parentView, tableName); conn.createStatement().execute(ddl); ddl = String.format(childViewTemplate, childView, parentView, ttl); conn.createStatement().execute(ddl); assertTTL(conn, tableName, TTL_EXPRESSION_NOT_DEFINED); assertTTL(conn, parentView, TTL_EXPRESSION_NOT_DEFINED); assertConditonTTL(conn, childView, ttl); // create an index on child view ddl = String.format(indexOnChildTemplate, indexName, childView); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); } } @Test public void testInListTTLExpr() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 varchar) TTL = '%s'"; String tableName = generateUniqueName(); String ttl = "col2 IN ('expired', 'cancelled')"; String query; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); query = String.format("select col1 from %s where id IN ('abc', 'fff')", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1", "col2")); } } @Test public void testPartialIndex() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 integer, col3 double, col4 varchar) TTL = '%s'"; String tableName = generateUniqueName(); String indexTemplate = "create index %s on %s (col1) " + "include (col2, col3, col4) where col1 > 50"; String indexName = generateUniqueName(); String ttl = "col2 > 100 AND col4='expired'"; String query; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); ddl = String.format(indexTemplate, indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); query = String.format("select col3 from %s where col1 > 60", tableName); validateScan(conn, tableName, query, ttl, true, Lists.newArrayList("0:col2", "0:col3", "0:col4")); } } @Test public void testUncoveredIndex() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 integer, col3 double, col4 varchar) TTL = '%s'"; String tableName = generateUniqueName(); String indexTemplate = "create uncovered index %s on %s (col1) "; String indexName = generateUniqueName(); String ttl = "col2 > 100 AND col4='expired'"; String query; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); ddl = String.format(indexTemplate, indexName, tableName); try { conn.createStatement().execute(ddl); fail("Should have thrown ColumnNotFoundException"); } catch (SQLException e) { assertTrue(e.getCause() instanceof ColumnNotFoundException); } indexTemplate = "create uncovered index %s on %s (col4, col2) "; ddl = String.format(indexTemplate, indexName, tableName); conn.createStatement().execute(ddl); assertConditonTTL(conn, indexName, ttl); } } @Test public void testCreatingIndexWithMissingExprCols() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 integer, col3 double, col4 varchar) TTL = '%s'"; String tableName = generateUniqueName(); String indexTemplate = "create index %s on %s (col1) include (col2)"; String indexName = generateUniqueName(); String ttl = "col2 > 100 AND col4='expired'"; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(ddl); ddl = String.format(indexTemplate, indexName, tableName); try { conn.createStatement().execute(ddl); fail("Should have thrown ColumnNotFoundException"); } catch (SQLException e) { assertTrue(e.getCause() instanceof ColumnNotFoundException); } } } @Test public void testSettingCondTTLOnTableWithIndexWithMissingExprCols() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 integer, col3 double, col4 varchar)"; String tableName = generateUniqueName(); String indexTemplate = "create index %s on %s (col1) include (col2)"; String indexName = generateUniqueName(); String ttl = "col2 > 100 AND col4='expired'"; try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName); conn.createStatement().execute(ddl); ddl = String.format(indexTemplate, indexName, tableName); conn.createStatement().execute(ddl); ddl = String.format("alter table %s set TTL = '%s'", tableName, retainSingleQuotes(ttl)); try { conn.createStatement().execute(ddl); fail("Should have thrown ColumnNotFoundException"); } catch (SQLException e) { assertTrue(e.getCause() instanceof ColumnNotFoundException); } } } @Test public void testScanColumns() throws Exception { String ddlTemplate = "create table %s (k1 bigint not null, k2 bigint not null," + "col1 varchar, col2 date constraint pk primary key (k1,k2 desc)) " + "COLUMN_ENCODED_BYTES=0, TTL = '%s'"; String ttl = "k1 > 5 AND col1 < 'zzzzzz'"; String tableName = generateUniqueName(); String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); try (Connection conn = DriverManager.getConnection(getUrl())) { conn.createStatement().execute(ddl); assertConditonTTL(conn, tableName, ttl); String query = String.format("select * from %s where k1 > 3", tableName); // select * so all columns should be read validateScan(conn, tableName, query, ttl, false, Collections.EMPTY_LIST); // all non pk columns in ttl expression should be added to scan query = String.format("select count(*) from %s where k1 > 3", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1")); // all non pk columns in ttl expression should be added query = String.format("select k1, k2 from %s where k1 > 3", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1")); // non pk columns and other non pk columns in ttl expression should be added to scan query = String.format("select col1, col2 from %s where k1 > 3", tableName); validateScan(conn, tableName, query, ttl, false, Lists.newArrayList("col1", "col2")); } } @Test public void testLatestRowVersion() throws Exception { String ddlTemplate = "create table %s (id varchar not null primary key, " + "col1 integer, col2 integer, col3 varchar) TTL = '%s'"; String tableName = generateUniqueName(); String ttl = "col2 > 100 AND col3='expired'"; long currentTS = EnvironmentEdgeManager.currentTimeMillis(); try (Connection conn = DriverManager.getConnection(getUrl())) { String ddl = String.format(ddlTemplate, tableName, retainSingleQuotes(ttl)); conn.createStatement().execute(ddl); PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); PTable table = pconn.getTable(tableName); int updateCount = 5; String id = "a"; ImmutableBytesPtr rowKey = new ImmutableBytesPtr(Bytes.toBytes(id)); List<Cell> updates = new ArrayList<>(); for (int i = 0; i < updateCount; ++i) { updates.addAll(generateUpdate(id, i, i * i, "val_" + i, currentTS + i * 10)); } // updates [ // lastUpdateTS - 40, // lastUpdateTS - 30, // lastUpdateTS - 20, // lastUpdateTS - 10, // lastUpdateTS // ] long lastupdateTS = currentTS + (updateCount - 1) * 10; CompiledConditionalTTLExpression ttlExpr = (CompiledConditionalTTLExpression) table.getCompiledTTLExpression(pconn); // case 1: no Deletes just multiple Put mutations List<Cell> row = Lists.newArrayList(updates); row.sort(CellComparator.getInstance()); List<Cell> latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(3, latestRowVersion.size()); // 3 columns for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS, cell.getTimestamp()); } // case 2 insert DeleteFamily at the top row = Lists.newArrayList(updates); KeyValue df = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), null, lastupdateTS + 5, KeyValue.Type.DeleteFamily, null); row.add(df); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertTrue(latestRowVersion.isEmpty()); // case 3 insert DeleteFamilyVersion at last TS row = Lists.newArrayList(updates); KeyValue dfv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), null, lastupdateTS, KeyValue.Type.DeleteFamilyVersion, null); row.add(dfv); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(3, latestRowVersion.size()); // 3 columns for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS - 10, cell.getTimestamp()); } // case 4 insert DeleteFamilyVersion at last TS, DeleteFamily in the middle row = Lists.newArrayList(updates); df = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), null, lastupdateTS - 25, KeyValue.Type.DeleteFamily, null); row.add(df); row.add(dfv); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(3, latestRowVersion.size()); // 3 columns for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS - 10, cell.getTimestamp()); } // case 5 multiple DeleteFamilyVersions row = Lists.newArrayList(updates); row.add(dfv); dfv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), null, lastupdateTS - 10, KeyValue.Type.DeleteFamilyVersion, null); row.add(dfv); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(3, latestRowVersion.size()); // 3 columns for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS - 20, cell.getTimestamp()); } // case 6 DeleteFamily in the middle row = Lists.newArrayList(updates); df = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), null, lastupdateTS - 5, KeyValue.Type.DeleteFamily, null); row.add(df); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(3, latestRowVersion.size()); // 3 columns for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS, cell.getTimestamp()); } // case 7 DeleteColumn row = Lists.newArrayList(updates); row.addAll(generateUpdate(id, 12, null, null, lastupdateTS + 10)); row.sort(CellComparator.getInstance()); latestRowVersion = ttlExpr.getLatestRowVersion(row); assertEquals(1, latestRowVersion.size()); // 1 column is non null for (Cell cell : latestRowVersion) { assertEquals(lastupdateTS + 10, cell.getTimestamp()); } } } private List<Cell> generateUpdate(String id, Integer col1, Integer col2, String col3, long ts) { List<Cell> update = Lists.newArrayList(); if (col1 != null) { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col1"), ts, KeyValue.Type.Put, Bytes.toBytes(col1)); update.add(kv); } else { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col1"), ts, KeyValue.Type.DeleteColumn, null); update.add(kv); } if (col2 != null) { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col2"), ts, KeyValue.Type.Put, Bytes.toBytes(col2)); update.add(kv); } else { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col2"), ts, KeyValue.Type.DeleteColumn, null); update.add(kv); } if (col3 != null) { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col3"), ts, KeyValue.Type.Put, Bytes.toBytes(col3)); update.add(kv); } else { KeyValue kv = new KeyValue(Bytes.toBytes(id), Bytes.toBytes("f"), Bytes.toBytes("col3"), ts, KeyValue.Type.DeleteColumn, null); update.add(kv); } return update; } }
googleapis/google-cloud-java
35,619
java-securitycenter-settings/google-cloud-securitycenter-settings/src/main/java/com/google/cloud/securitycenter/settings/v1beta1/stub/SecurityCenterSettingsServiceStubSettings.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.securitycenter.settings.v1beta1.stub; import static com.google.cloud.securitycenter.settings.v1beta1.SecurityCenterSettingsServiceClient.ListComponentsPagedResponse; import static com.google.cloud.securitycenter.settings.v1beta1.SecurityCenterSettingsServiceClient.ListDetectorsPagedResponse; 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.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.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.securitycenter.settings.v1beta1.BatchCalculateEffectiveSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.BatchCalculateEffectiveSettingsResponse; import com.google.cloud.securitycenter.settings.v1beta1.BatchGetSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.BatchGetSettingsResponse; import com.google.cloud.securitycenter.settings.v1beta1.CalculateEffectiveComponentSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.CalculateEffectiveSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ComponentSettings; import com.google.cloud.securitycenter.settings.v1beta1.Detector; import com.google.cloud.securitycenter.settings.v1beta1.GetComponentSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.GetServiceAccountRequest; import com.google.cloud.securitycenter.settings.v1beta1.GetSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ListComponentsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ListComponentsResponse; import com.google.cloud.securitycenter.settings.v1beta1.ListDetectorsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ListDetectorsResponse; import com.google.cloud.securitycenter.settings.v1beta1.ResetComponentSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ResetSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.ServiceAccount; import com.google.cloud.securitycenter.settings.v1beta1.Settings; import com.google.cloud.securitycenter.settings.v1beta1.UpdateComponentSettingsRequest; import com.google.cloud.securitycenter.settings.v1beta1.UpdateSettingsRequest; 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.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 SecurityCenterSettingsServiceStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (securitycenter.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 getServiceAccount: * * <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 * SecurityCenterSettingsServiceStubSettings.Builder securityCenterSettingsServiceSettingsBuilder = * SecurityCenterSettingsServiceStubSettings.newBuilder(); * securityCenterSettingsServiceSettingsBuilder * .getServiceAccountSettings() * .setRetrySettings( * securityCenterSettingsServiceSettingsBuilder * .getServiceAccountSettings() * .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()); * SecurityCenterSettingsServiceStubSettings securityCenterSettingsServiceSettings = * securityCenterSettingsServiceSettingsBuilder.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. */ @BetaApi @Generated("by gapic-generator-java") public class SecurityCenterSettingsServiceStubSettings extends StubSettings<SecurityCenterSettingsServiceStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build(); private final UnaryCallSettings<GetServiceAccountRequest, ServiceAccount> getServiceAccountSettings; private final UnaryCallSettings<GetSettingsRequest, Settings> getSettingsSettings; private final UnaryCallSettings<UpdateSettingsRequest, Settings> updateSettingsSettings; private final UnaryCallSettings<ResetSettingsRequest, Empty> resetSettingsSettings; private final UnaryCallSettings<BatchGetSettingsRequest, BatchGetSettingsResponse> batchGetSettingsSettings; private final UnaryCallSettings<CalculateEffectiveSettingsRequest, Settings> calculateEffectiveSettingsSettings; private final UnaryCallSettings< BatchCalculateEffectiveSettingsRequest, BatchCalculateEffectiveSettingsResponse> batchCalculateEffectiveSettingsSettings; private final UnaryCallSettings<GetComponentSettingsRequest, ComponentSettings> getComponentSettingsSettings; private final UnaryCallSettings<UpdateComponentSettingsRequest, ComponentSettings> updateComponentSettingsSettings; private final UnaryCallSettings<ResetComponentSettingsRequest, Empty> resetComponentSettingsSettings; private final UnaryCallSettings<CalculateEffectiveComponentSettingsRequest, ComponentSettings> calculateEffectiveComponentSettingsSettings; private final PagedCallSettings< ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse> listDetectorsSettings; private final PagedCallSettings< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse> listComponentsSettings; private static final PagedListDescriptor<ListDetectorsRequest, ListDetectorsResponse, Detector> LIST_DETECTORS_PAGE_STR_DESC = new PagedListDescriptor<ListDetectorsRequest, ListDetectorsResponse, Detector>() { @Override public String emptyToken() { return ""; } @Override public ListDetectorsRequest injectToken(ListDetectorsRequest payload, String token) { return ListDetectorsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListDetectorsRequest injectPageSize(ListDetectorsRequest payload, int pageSize) { return ListDetectorsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListDetectorsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListDetectorsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Detector> extractResources(ListDetectorsResponse payload) { return payload.getDetectorsList(); } }; private static final PagedListDescriptor<ListComponentsRequest, ListComponentsResponse, String> LIST_COMPONENTS_PAGE_STR_DESC = new PagedListDescriptor<ListComponentsRequest, ListComponentsResponse, String>() { @Override public String emptyToken() { return ""; } @Override public ListComponentsRequest injectToken(ListComponentsRequest payload, String token) { return ListComponentsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListComponentsRequest injectPageSize( ListComponentsRequest payload, int pageSize) { return ListComponentsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListComponentsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListComponentsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<String> extractResources(ListComponentsResponse payload) { return payload.getComponentsList(); } }; private static final PagedListResponseFactory< ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse> LIST_DETECTORS_PAGE_STR_FACT = new PagedListResponseFactory< ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse>() { @Override public ApiFuture<ListDetectorsPagedResponse> getFuturePagedResponse( UnaryCallable<ListDetectorsRequest, ListDetectorsResponse> callable, ListDetectorsRequest request, ApiCallContext context, ApiFuture<ListDetectorsResponse> futureResponse) { PageContext<ListDetectorsRequest, ListDetectorsResponse, Detector> pageContext = PageContext.create(callable, LIST_DETECTORS_PAGE_STR_DESC, request, context); return ListDetectorsPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse> LIST_COMPONENTS_PAGE_STR_FACT = new PagedListResponseFactory< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse>() { @Override public ApiFuture<ListComponentsPagedResponse> getFuturePagedResponse( UnaryCallable<ListComponentsRequest, ListComponentsResponse> callable, ListComponentsRequest request, ApiCallContext context, ApiFuture<ListComponentsResponse> futureResponse) { PageContext<ListComponentsRequest, ListComponentsResponse, String> pageContext = PageContext.create(callable, LIST_COMPONENTS_PAGE_STR_DESC, request, context); return ListComponentsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to getServiceAccount. */ public UnaryCallSettings<GetServiceAccountRequest, ServiceAccount> getServiceAccountSettings() { return getServiceAccountSettings; } /** Returns the object with the settings used for calls to getSettings. */ public UnaryCallSettings<GetSettingsRequest, Settings> getSettingsSettings() { return getSettingsSettings; } /** Returns the object with the settings used for calls to updateSettings. */ public UnaryCallSettings<UpdateSettingsRequest, Settings> updateSettingsSettings() { return updateSettingsSettings; } /** Returns the object with the settings used for calls to resetSettings. */ public UnaryCallSettings<ResetSettingsRequest, Empty> resetSettingsSettings() { return resetSettingsSettings; } /** Returns the object with the settings used for calls to batchGetSettings. */ public UnaryCallSettings<BatchGetSettingsRequest, BatchGetSettingsResponse> batchGetSettingsSettings() { return batchGetSettingsSettings; } /** Returns the object with the settings used for calls to calculateEffectiveSettings. */ public UnaryCallSettings<CalculateEffectiveSettingsRequest, Settings> calculateEffectiveSettingsSettings() { return calculateEffectiveSettingsSettings; } /** Returns the object with the settings used for calls to batchCalculateEffectiveSettings. */ public UnaryCallSettings< BatchCalculateEffectiveSettingsRequest, BatchCalculateEffectiveSettingsResponse> batchCalculateEffectiveSettingsSettings() { return batchCalculateEffectiveSettingsSettings; } /** Returns the object with the settings used for calls to getComponentSettings. */ public UnaryCallSettings<GetComponentSettingsRequest, ComponentSettings> getComponentSettingsSettings() { return getComponentSettingsSettings; } /** Returns the object with the settings used for calls to updateComponentSettings. */ public UnaryCallSettings<UpdateComponentSettingsRequest, ComponentSettings> updateComponentSettingsSettings() { return updateComponentSettingsSettings; } /** Returns the object with the settings used for calls to resetComponentSettings. */ public UnaryCallSettings<ResetComponentSettingsRequest, Empty> resetComponentSettingsSettings() { return resetComponentSettingsSettings; } /** Returns the object with the settings used for calls to calculateEffectiveComponentSettings. */ public UnaryCallSettings<CalculateEffectiveComponentSettingsRequest, ComponentSettings> calculateEffectiveComponentSettingsSettings() { return calculateEffectiveComponentSettingsSettings; } /** Returns the object with the settings used for calls to listDetectors. */ public PagedCallSettings<ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse> listDetectorsSettings() { return listDetectorsSettings; } /** Returns the object with the settings used for calls to listComponents. */ public PagedCallSettings< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse> listComponentsSettings() { return listComponentsSettings; } public SecurityCenterSettingsServiceStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcSecurityCenterSettingsServiceStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "securitycenter"; } /** 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 "securitycenter.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "securitycenter.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 InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(SecurityCenterSettingsServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** 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 SecurityCenterSettingsServiceStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); getServiceAccountSettings = settingsBuilder.getServiceAccountSettings().build(); getSettingsSettings = settingsBuilder.getSettingsSettings().build(); updateSettingsSettings = settingsBuilder.updateSettingsSettings().build(); resetSettingsSettings = settingsBuilder.resetSettingsSettings().build(); batchGetSettingsSettings = settingsBuilder.batchGetSettingsSettings().build(); calculateEffectiveSettingsSettings = settingsBuilder.calculateEffectiveSettingsSettings().build(); batchCalculateEffectiveSettingsSettings = settingsBuilder.batchCalculateEffectiveSettingsSettings().build(); getComponentSettingsSettings = settingsBuilder.getComponentSettingsSettings().build(); updateComponentSettingsSettings = settingsBuilder.updateComponentSettingsSettings().build(); resetComponentSettingsSettings = settingsBuilder.resetComponentSettingsSettings().build(); calculateEffectiveComponentSettingsSettings = settingsBuilder.calculateEffectiveComponentSettingsSettings().build(); listDetectorsSettings = settingsBuilder.listDetectorsSettings().build(); listComponentsSettings = settingsBuilder.listComponentsSettings().build(); } /** Builder for SecurityCenterSettingsServiceStubSettings. */ public static class Builder extends StubSettings.Builder<SecurityCenterSettingsServiceStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<GetServiceAccountRequest, ServiceAccount> getServiceAccountSettings; private final UnaryCallSettings.Builder<GetSettingsRequest, Settings> getSettingsSettings; private final UnaryCallSettings.Builder<UpdateSettingsRequest, Settings> updateSettingsSettings; private final UnaryCallSettings.Builder<ResetSettingsRequest, Empty> resetSettingsSettings; private final UnaryCallSettings.Builder<BatchGetSettingsRequest, BatchGetSettingsResponse> batchGetSettingsSettings; private final UnaryCallSettings.Builder<CalculateEffectiveSettingsRequest, Settings> calculateEffectiveSettingsSettings; private final UnaryCallSettings.Builder< BatchCalculateEffectiveSettingsRequest, BatchCalculateEffectiveSettingsResponse> batchCalculateEffectiveSettingsSettings; private final UnaryCallSettings.Builder<GetComponentSettingsRequest, ComponentSettings> getComponentSettingsSettings; private final UnaryCallSettings.Builder<UpdateComponentSettingsRequest, ComponentSettings> updateComponentSettingsSettings; private final UnaryCallSettings.Builder<ResetComponentSettingsRequest, Empty> resetComponentSettingsSettings; private final UnaryCallSettings.Builder< CalculateEffectiveComponentSettingsRequest, ComponentSettings> calculateEffectiveComponentSettingsSettings; private final PagedCallSettings.Builder< ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse> listDetectorsSettings; private final PagedCallSettings.Builder< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse> listComponentsSettings; 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))); 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); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); getServiceAccountSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); resetSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); batchGetSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); calculateEffectiveSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); batchCalculateEffectiveSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getComponentSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateComponentSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); resetComponentSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); calculateEffectiveComponentSettingsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); listDetectorsSettings = PagedCallSettings.newBuilder(LIST_DETECTORS_PAGE_STR_FACT); listComponentsSettings = PagedCallSettings.newBuilder(LIST_COMPONENTS_PAGE_STR_FACT); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getServiceAccountSettings, getSettingsSettings, updateSettingsSettings, resetSettingsSettings, batchGetSettingsSettings, calculateEffectiveSettingsSettings, batchCalculateEffectiveSettingsSettings, getComponentSettingsSettings, updateComponentSettingsSettings, resetComponentSettingsSettings, calculateEffectiveComponentSettingsSettings, listDetectorsSettings, listComponentsSettings); initDefaults(this); } protected Builder(SecurityCenterSettingsServiceStubSettings settings) { super(settings); getServiceAccountSettings = settings.getServiceAccountSettings.toBuilder(); getSettingsSettings = settings.getSettingsSettings.toBuilder(); updateSettingsSettings = settings.updateSettingsSettings.toBuilder(); resetSettingsSettings = settings.resetSettingsSettings.toBuilder(); batchGetSettingsSettings = settings.batchGetSettingsSettings.toBuilder(); calculateEffectiveSettingsSettings = settings.calculateEffectiveSettingsSettings.toBuilder(); batchCalculateEffectiveSettingsSettings = settings.batchCalculateEffectiveSettingsSettings.toBuilder(); getComponentSettingsSettings = settings.getComponentSettingsSettings.toBuilder(); updateComponentSettingsSettings = settings.updateComponentSettingsSettings.toBuilder(); resetComponentSettingsSettings = settings.resetComponentSettingsSettings.toBuilder(); calculateEffectiveComponentSettingsSettings = settings.calculateEffectiveComponentSettingsSettings.toBuilder(); listDetectorsSettings = settings.listDetectorsSettings.toBuilder(); listComponentsSettings = settings.listComponentsSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getServiceAccountSettings, getSettingsSettings, updateSettingsSettings, resetSettingsSettings, batchGetSettingsSettings, calculateEffectiveSettingsSettings, batchCalculateEffectiveSettingsSettings, getComponentSettingsSettings, updateComponentSettingsSettings, resetComponentSettingsSettings, calculateEffectiveComponentSettingsSettings, listDetectorsSettings, listComponentsSettings); } 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 .getServiceAccountSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .getSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .updateSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .resetSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .batchGetSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .calculateEffectiveSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .batchCalculateEffectiveSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .getComponentSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .updateComponentSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .resetComponentSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .calculateEffectiveComponentSettingsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .listDetectorsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .listComponentsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); 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 getServiceAccount. */ public UnaryCallSettings.Builder<GetServiceAccountRequest, ServiceAccount> getServiceAccountSettings() { return getServiceAccountSettings; } /** Returns the builder for the settings used for calls to getSettings. */ public UnaryCallSettings.Builder<GetSettingsRequest, Settings> getSettingsSettings() { return getSettingsSettings; } /** Returns the builder for the settings used for calls to updateSettings. */ public UnaryCallSettings.Builder<UpdateSettingsRequest, Settings> updateSettingsSettings() { return updateSettingsSettings; } /** Returns the builder for the settings used for calls to resetSettings. */ public UnaryCallSettings.Builder<ResetSettingsRequest, Empty> resetSettingsSettings() { return resetSettingsSettings; } /** Returns the builder for the settings used for calls to batchGetSettings. */ public UnaryCallSettings.Builder<BatchGetSettingsRequest, BatchGetSettingsResponse> batchGetSettingsSettings() { return batchGetSettingsSettings; } /** Returns the builder for the settings used for calls to calculateEffectiveSettings. */ public UnaryCallSettings.Builder<CalculateEffectiveSettingsRequest, Settings> calculateEffectiveSettingsSettings() { return calculateEffectiveSettingsSettings; } /** Returns the builder for the settings used for calls to batchCalculateEffectiveSettings. */ public UnaryCallSettings.Builder< BatchCalculateEffectiveSettingsRequest, BatchCalculateEffectiveSettingsResponse> batchCalculateEffectiveSettingsSettings() { return batchCalculateEffectiveSettingsSettings; } /** Returns the builder for the settings used for calls to getComponentSettings. */ public UnaryCallSettings.Builder<GetComponentSettingsRequest, ComponentSettings> getComponentSettingsSettings() { return getComponentSettingsSettings; } /** Returns the builder for the settings used for calls to updateComponentSettings. */ public UnaryCallSettings.Builder<UpdateComponentSettingsRequest, ComponentSettings> updateComponentSettingsSettings() { return updateComponentSettingsSettings; } /** Returns the builder for the settings used for calls to resetComponentSettings. */ public UnaryCallSettings.Builder<ResetComponentSettingsRequest, Empty> resetComponentSettingsSettings() { return resetComponentSettingsSettings; } /** * Returns the builder for the settings used for calls to calculateEffectiveComponentSettings. */ public UnaryCallSettings.Builder<CalculateEffectiveComponentSettingsRequest, ComponentSettings> calculateEffectiveComponentSettingsSettings() { return calculateEffectiveComponentSettingsSettings; } /** Returns the builder for the settings used for calls to listDetectors. */ public PagedCallSettings.Builder< ListDetectorsRequest, ListDetectorsResponse, ListDetectorsPagedResponse> listDetectorsSettings() { return listDetectorsSettings; } /** Returns the builder for the settings used for calls to listComponents. */ public PagedCallSettings.Builder< ListComponentsRequest, ListComponentsResponse, ListComponentsPagedResponse> listComponentsSettings() { return listComponentsSettings; } @Override public SecurityCenterSettingsServiceStubSettings build() throws IOException { return new SecurityCenterSettingsServiceStubSettings(this); } } }
apache/solr
35,099
solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/FacetStream.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 java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.impl.ClusterStateProvider; import org.apache.solr.client.solrj.io.SolrClientCache; import org.apache.solr.client.solrj.io.Tuple; import org.apache.solr.client.solrj.io.comp.ComparatorOrder; import org.apache.solr.client.solrj.io.comp.FieldComparator; import org.apache.solr.client.solrj.io.comp.MultipleFieldComparator; import org.apache.solr.client.solrj.io.comp.StreamComparator; import org.apache.solr.client.solrj.io.stream.expr.Explanation; import org.apache.solr.client.solrj.io.stream.expr.Explanation.ExpressionType; import org.apache.solr.client.solrj.io.stream.expr.Expressible; import org.apache.solr.client.solrj.io.stream.expr.StreamExplanation; import org.apache.solr.client.solrj.io.stream.expr.StreamExpression; import org.apache.solr.client.solrj.io.stream.expr.StreamExpressionNamedParameter; import org.apache.solr.client.solrj.io.stream.expr.StreamExpressionParameter; import org.apache.solr.client.solrj.io.stream.expr.StreamExpressionValue; import org.apache.solr.client.solrj.io.stream.expr.StreamFactory; import org.apache.solr.client.solrj.io.stream.metrics.Bucket; import org.apache.solr.client.solrj.io.stream.metrics.CountMetric; import org.apache.solr.client.solrj.io.stream.metrics.Metric; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.CollectionUtil; import org.apache.solr.common.util.EnvUtils; import org.apache.solr.common.util.NamedList; /** * The FacetStream abstracts the output from the JSON facet API as a Stream of Tuples. This provides * an alternative to the RollupStream which uses Map/Reduce to perform aggregations. * * @since 6.0.0 */ public class FacetStream extends TupleStream implements Expressible, ParallelMetricsRollup { private static final long serialVersionUID = 1; // allow client apps to disable the auto-plist via system property if they want to turn it off // globally static final boolean defaultTieredEnabled = EnvUtils.getPropertyAsBool("solr.streamingexpressions.facet.tiered.enabled", true); static final String TIERED_PARAM = "tiered"; private Bucket[] buckets; private Metric[] metrics; private int rows; private int offset; private int overfetch; private int bucketSizeLimit; private boolean refine; private String method; private FieldComparator[] bucketSorts; private List<Tuple> tuples = new ArrayList<Tuple>(); private int index; private String zkHost; private ModifiableSolrParams params; private String collection; private boolean resortNeeded; private boolean serializeBucketSizeLimit; protected transient SolrClientCache clientCache; private transient boolean doCloseCache; protected transient TupleStream parallelizedStream; protected transient StreamContext context; public FacetStream( String zkHost, String collection, SolrParams params, Bucket[] buckets, Metric[] metrics, FieldComparator[] bucketSorts, int bucketSizeLimit) throws IOException { if (bucketSizeLimit == -1) { bucketSizeLimit = Integer.MAX_VALUE; } init( collection, params, buckets, bucketSorts, metrics, bucketSizeLimit, 0, bucketSizeLimit, false, null, true, 0, zkHost); } public FacetStream(StreamExpression expression, StreamFactory factory) throws IOException { // grab all parameters out String collectionName = factory.getValueOperand(expression, 0); if (collectionName.indexOf('"') > -1) { collectionName = collectionName.replace("\"", "").replace(" ", ""); } List<StreamExpressionNamedParameter> namedParams = factory.getNamedOperands(expression); StreamExpressionNamedParameter bucketExpression = factory.getNamedOperand(expression, "buckets"); StreamExpressionNamedParameter bucketSortExpression = factory.getNamedOperand(expression, "bucketSorts"); List<StreamExpression> metricExpressions = factory.getExpressionOperandsRepresentingTypes(expression, Expressible.class, Metric.class); StreamExpressionNamedParameter bucketLimitExpression = factory.getNamedOperand(expression, "bucketSizeLimit"); StreamExpressionNamedParameter zkHostExpression = factory.getNamedOperand(expression, "zkHost"); StreamExpressionNamedParameter rowsExpression = factory.getNamedOperand(expression, "rows"); StreamExpressionNamedParameter offsetExpression = factory.getNamedOperand(expression, "offset"); StreamExpressionNamedParameter overfetchExpression = factory.getNamedOperand(expression, "overfetch"); StreamExpressionNamedParameter refineExpression = factory.getNamedOperand(expression, "refine"); StreamExpressionNamedParameter methodExpression = factory.getNamedOperand(expression, "method"); // Validate there are no unknown parameters if (expression.getParameters().size() != 1 + namedParams.size() + metricExpressions.size()) { throw new IOException( String.format(Locale.ROOT, "invalid expression %s - unknown operands found", expression)); } // Collection Name if (null == collectionName) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - collectionName expected as first operand", expression)); } // Named parameters - passed directly to solr as SolrParams if (0 == namedParams.size()) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - at least one named parameter expected. eg. 'q=*:*'", expression)); } // pull out known named params ModifiableSolrParams params = new ModifiableSolrParams(); for (StreamExpressionNamedParameter namedParam : namedParams) { if (!namedParam.getName().equals("zkHost") && !namedParam.getName().equals("buckets") && !namedParam.getName().equals("bucketSorts") && !namedParam.getName().equals("bucketSizeLimit") && !namedParam.getName().equals("method") && !namedParam.getName().equals("offset") && !namedParam.getName().equals("rows") && !namedParam.getName().equals("refine") && !namedParam.getName().equals("overfetch")) { params.add(namedParam.getName(), namedParam.getParameter().toString().trim()); } } if (params.get("q") == null) { params.set("q", "*:*"); } // buckets, required - comma separated Bucket[] buckets = null; if (null != bucketExpression) { if (bucketExpression.getParameter() instanceof StreamExpressionValue) { String[] keys = ((StreamExpressionValue) bucketExpression.getParameter()).getValue().split(","); if (0 != keys.length) { buckets = new Bucket[keys.length]; for (int idx = 0; idx < keys.length; ++idx) { buckets[idx] = new Bucket(keys[idx].trim()); } } } } if (null == buckets) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - at least one bucket expected. eg. 'buckets=\"name\"'", expression)); } // Construct the metrics Metric[] metrics = new Metric[metricExpressions.size()]; for (int idx = 0; idx < metricExpressions.size(); ++idx) { metrics[idx] = factory.constructMetric(metricExpressions.get(idx)); } if (metrics.length == 0) { metrics = new Metric[1]; metrics[0] = new CountMetric(); } String bucketSortString = null; if (bucketSortExpression == null) { bucketSortString = metrics[0].getIdentifier() + " desc"; } else { bucketSortString = ((StreamExpressionValue) bucketSortExpression.getParameter()).getValue(); if (bucketSortString.contains("(") && metricExpressions.size() == 0 && (!bucketSortString.equals("count(*) desc") && !bucketSortString.equals("count(*) asc"))) { // Attempting bucket sort on a metric that is not going to be calculated. throw new IOException( String.format( Locale.ROOT, "invalid expression %s - the bucketSort is being performed on a metric that is not being calculated.", expression)); } } FieldComparator[] bucketSorts = parseBucketSorts(bucketSortString, buckets); if (null == bucketSorts || 0 == bucketSorts.length) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - at least one bucket sort expected. eg. 'bucketSorts=\"name asc\"'", expression)); } boolean refine = false; if (refineExpression != null) { String refineStr = ((StreamExpressionValue) refineExpression.getParameter()).getValue(); if (refineStr != null) { refine = Boolean.parseBoolean(refineStr); } } if (bucketLimitExpression != null && (rowsExpression != null || offsetExpression != null || overfetchExpression != null)) { throw new IOException("bucketSizeLimit is incompatible with rows, offset and overfetch."); } String methodStr = null; if (methodExpression != null) { methodStr = ((StreamExpressionValue) methodExpression.getParameter()).getValue(); } int overfetchInt = 250; if (overfetchExpression != null) { String overfetchStr = ((StreamExpressionValue) overfetchExpression.getParameter()).getValue(); overfetchInt = Integer.parseInt(overfetchStr); } int offsetInt = 0; if (offsetExpression != null) { String offsetStr = ((StreamExpressionValue) offsetExpression.getParameter()).getValue(); offsetInt = Integer.parseInt(offsetStr); } int rowsInt = Integer.MIN_VALUE; int bucketLimit = Integer.MIN_VALUE; boolean bucketLimitSet = false; if (null != rowsExpression) { String rowsStr = ((StreamExpressionValue) rowsExpression.getParameter()).getValue(); try { rowsInt = Integer.parseInt(rowsStr); if (rowsInt <= 0 && rowsInt != -1) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - limit '%s' must be greater than 0 or -1.", expression, rowsStr)); } // Rows is set so configure the bucketLimitSize if (rowsInt == -1) { bucketLimit = rowsInt = Integer.MAX_VALUE; } else if (overfetchInt == -1) { bucketLimit = Integer.MAX_VALUE; } else { bucketLimit = offsetInt + overfetchInt + rowsInt; } } catch (NumberFormatException e) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - limit '%s' is not a valid integer.", expression, rowsStr)); } } if (bucketLimitExpression != null) { String bucketLimitStr = ((StreamExpressionValue) bucketLimitExpression.getParameter()).getValue(); try { bucketLimit = Integer.parseInt(bucketLimitStr); bucketLimitSet = true; if (bucketLimit <= 0 && bucketLimit != -1) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - bucketSizeLimit '%s' must be greater than 0 or -1.", expression, bucketLimitStr)); } // Bucket limit is set. So set rows. if (bucketLimit == -1) { rowsInt = bucketLimit = Integer.MAX_VALUE; } else { rowsInt = bucketLimit; } } catch (NumberFormatException e) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - bucketSizeLimit '%s' is not a valid integer.", expression, bucketLimitStr)); } } if (rowsExpression == null && bucketLimitExpression == null) { rowsInt = 10; if (overfetchInt == -1) { bucketLimit = Integer.MAX_VALUE; } else { bucketLimit = offsetInt + overfetchInt + rowsInt; } } // zkHost, optional - if not provided then will look into factory list to get String zkHost = null; if (null == zkHostExpression) { zkHost = factory.getCollectionZkHost(collectionName); if (zkHost == null) { zkHost = factory.getDefaultZkHost(); } } else if (zkHostExpression.getParameter() instanceof StreamExpressionValue) { zkHost = ((StreamExpressionValue) zkHostExpression.getParameter()).getValue(); } if (null == zkHost) { throw new IOException( String.format( Locale.ROOT, "invalid expression %s - zkHost not found for collection '%s'", expression, collectionName)); } // We've got all the required items init( collectionName, params, buckets, bucketSorts, metrics, rowsInt, offsetInt, bucketLimit, refine, methodStr, bucketLimitSet, overfetchInt, zkHost); } // see usage in parallelize method private FacetStream() {} public int getBucketSizeLimit() { return this.bucketSizeLimit; } public int getRows() { return this.rows; } public int getOffset() { return this.offset; } public int getOverfetch() { return this.overfetch; } public Bucket[] getBuckets() { return this.buckets; } public String getCollection() { return this.collection; } private FieldComparator[] parseBucketSorts(String bucketSortString, Bucket[] buckets) throws IOException { String[] sorts = parseSorts(bucketSortString); FieldComparator[] comps = new FieldComparator[sorts.length]; for (int i = 0; i < sorts.length; i++) { String s = sorts[i]; String fieldName = null; String order = null; if (s.endsWith("asc") || s.endsWith("ASC")) { order = "asc"; fieldName = s.substring(0, s.length() - 3).trim().replace(" ", ""); } else if (s.endsWith("desc") || s.endsWith("DESC")) { order = "desc"; fieldName = s.substring(0, s.length() - 4).trim().replace(" ", ""); } else { throw new IOException( String.format( Locale.ROOT, "invalid expression - bad bucketSort '%s'.", bucketSortString)); } comps[i] = new FieldComparator( fieldName, order.equalsIgnoreCase("asc") ? ComparatorOrder.ASCENDING : ComparatorOrder.DESCENDING); } return comps; } private String[] parseSorts(String sortString) { List<String> sorts = new ArrayList<>(); boolean inParam = false; StringBuilder buff = new StringBuilder(); for (int i = 0; i < sortString.length(); i++) { char c = sortString.charAt(i); if (c == '(') { inParam = true; buff.append(c); } else if (c == ')') { inParam = false; buff.append(c); } else if (c == ',' && !inParam) { sorts.add(buff.toString().trim()); buff = new StringBuilder(); } else { buff.append(c); } } if (buff.length() > 0) { sorts.add(buff.toString()); } return sorts.toArray(new String[0]); } private void init( String collection, SolrParams params, Bucket[] buckets, FieldComparator[] bucketSorts, Metric[] metrics, int rows, int offset, int bucketSizeLimit, boolean refine, String method, boolean serializeBucketSizeLimit, int overfetch, String zkHost) throws IOException { this.zkHost = zkHost; this.params = new ModifiableSolrParams(params); this.buckets = buckets; this.metrics = metrics; this.rows = rows; this.offset = offset; this.refine = refine; this.bucketSizeLimit = bucketSizeLimit; this.collection = collection; this.bucketSorts = bucketSorts; this.method = method; this.serializeBucketSizeLimit = serializeBucketSizeLimit; this.overfetch = overfetch; // In a facet world it only makes sense to have the same field name in all the sorters // Because FieldComparator allows for left and right field names we will need to validate // that they are the same for (FieldComparator sort : bucketSorts) { if (sort.hasDifferentFieldNames()) { throw new IOException( "Invalid FacetStream - all sorts must be constructed with a single field name."); } } } @Override public StreamExpressionParameter toExpression(StreamFactory factory) throws IOException { // function name StreamExpression expression = new StreamExpression(factory.getFunctionName(this.getClass())); // collection if (collection.indexOf(',') > -1) { expression.addParameter("\"" + collection + "\""); } else { expression.addParameter(collection); } // parameters for (Entry<String, String[]> param : params.getMap().entrySet()) { for (String val : param.getValue()) { expression.addParameter(new StreamExpressionNamedParameter(param.getKey(), val)); } } // buckets { StringBuilder builder = new StringBuilder(); for (Bucket bucket : buckets) { if (0 != builder.length()) { builder.append(","); } builder.append(bucket.toString()); } expression.addParameter(new StreamExpressionNamedParameter("buckets", builder.toString())); } // bucketSorts { StringBuilder builder = new StringBuilder(); for (FieldComparator sort : bucketSorts) { if (0 != builder.length()) { builder.append(","); } builder.append(sort.toExpression(factory)); } expression.addParameter( new StreamExpressionNamedParameter("bucketSorts", builder.toString())); } // metrics for (Metric metric : metrics) { expression.addParameter(metric.toExpression(factory)); } if (serializeBucketSizeLimit) { if (bucketSizeLimit == Integer.MAX_VALUE) { expression.addParameter( new StreamExpressionNamedParameter("bucketSizeLimit", Integer.toString(-1))); } else { expression.addParameter( new StreamExpressionNamedParameter( "bucketSizeLimit", Integer.toString(bucketSizeLimit))); } } else { if (rows == Integer.MAX_VALUE) { expression.addParameter(new StreamExpressionNamedParameter("rows", Integer.toString(-1))); } else { expression.addParameter(new StreamExpressionNamedParameter("rows", Integer.toString(rows))); } expression.addParameter( new StreamExpressionNamedParameter("offset", Integer.toString(offset))); if (overfetch == Integer.MAX_VALUE) { expression.addParameter( new StreamExpressionNamedParameter("overfetch", Integer.toString(-1))); } else { expression.addParameter( new StreamExpressionNamedParameter("overfetch", Integer.toString(overfetch))); } } if (method != null) { expression.addParameter(new StreamExpressionNamedParameter("method", this.method)); } // zkHost expression.addParameter(new StreamExpressionNamedParameter("zkHost", zkHost)); return expression; } @Override public Explanation toExplanation(StreamFactory factory) throws IOException { StreamExplanation explanation = new StreamExplanation(getStreamNodeId().toString()); explanation.setFunctionName(factory.getFunctionName(this.getClass())); explanation.setImplementingClass(this.getClass().getName()); explanation.setExpressionType(ExpressionType.STREAM_SOURCE); explanation.setExpression(toExpression(factory).toString()); // child is a datastore so add it at this point StreamExplanation child = new StreamExplanation(getStreamNodeId() + "-datastore"); child.setFunctionName(String.format(Locale.ROOT, "solr (%s)", collection)); // TODO: fix this so we know the # of workers - check with Joel about a Topic's ability to be in // a parallel stream. child.setImplementingClass("Solr/Lucene"); child.setExpressionType(ExpressionType.DATASTORE); child.setExpression( params.stream() .map( e -> String.format(Locale.ROOT, "%s=%s", e.getKey(), Arrays.toString(e.getValue()))) .collect(Collectors.joining(","))); explanation.addChild(child); return explanation; } @Override public void setStreamContext(StreamContext context) { this.context = context; this.clientCache = context.getSolrClientCache(); } @Override public List<TupleStream> children() { return new ArrayList<>(); } @Override public void open() throws IOException { if (clientCache == null) { doCloseCache = true; clientCache = new SolrClientCache(); } else { doCloseCache = false; } var cloudSolrClient = clientCache.getCloudSolrClient(zkHost); // Parallelize the facet expression across multiple collections for an alias using plist if // possible if (params.getBool(TIERED_PARAM, defaultTieredEnabled)) { ClusterStateProvider clusterStateProvider = cloudSolrClient.getClusterStateProvider(); final List<String> resolved = clusterStateProvider != null ? clusterStateProvider.resolveAlias(collection) : null; if (resolved != null && resolved.size() > 1) { Optional<TupleStream> maybeParallelize = openParallelStream(context, resolved, metrics); if (maybeParallelize.isPresent()) { this.parallelizedStream = maybeParallelize.get(); return; // we're using a plist to parallelize the facet operation else, there's a metric that // we can't rollup over the plist results safely. no plist for you! } } } FieldComparator[] adjustedSorts = adjustSorts(buckets, bucketSorts); this.resortNeeded = resortNeeded(adjustedSorts); String json = getJsonFacetString(buckets, metrics, adjustedSorts, method, refine, bucketSizeLimit); assert expectedJson(json); ModifiableSolrParams paramsLoc = new ModifiableSolrParams(params); paramsLoc.set("json.facet", json); paramsLoc.set("rows", "0"); QueryRequest request = new QueryRequest(paramsLoc, SolrRequest.METHOD.POST); if (paramsLoc.get("lb.proxy") != null) { request.setPath("/" + collection + "/select"); } try { NamedList<?> response = cloudSolrClient.request(request, collection); getTuples(response, buckets, metrics); if (resortNeeded) { tuples.sort(getStreamSort()); } index = this.offset; } catch (Exception e) { throw new IOException(e); } } private boolean expectedJson(String json) { if (this.method != null) { if (!json.contains("\"method\":\"" + this.method + "\"")) { return false; } } if (this.refine) { if (!json.contains("\"refine\":true")) { return false; } } if (serializeBucketSizeLimit) { if (!json.contains("\"limit\":" + bucketSizeLimit)) { return false; } } else { if (!json.contains("\"limit\":" + (this.rows + this.offset + this.overfetch))) { return false; } } for (Bucket bucket : buckets) { if (!json.contains("\"" + bucket.toString() + "\":")) { return false; } } for (Metric metric : metrics) { String func = metric.getFunctionName(); if (!func.equals("count") && !func.equals("per") && !func.equals("std") && !func.equals("countDist")) { if (!json.contains(metric.getIdentifier())) { return false; } } } return true; } @Override public void close() throws IOException { if (doCloseCache) { clientCache.close(); } } @Override public Tuple read() throws IOException { // if we're parallelizing the facet expression over multiple collections with plist, // then delegate the read operation to that stream instead if (parallelizedStream != null) { return parallelizedStream.read(); } if (index < tuples.size() && index < (offset + rows)) { Tuple tuple = tuples.get(index); ++index; return tuple; } else { Tuple tuple = Tuple.EOF(); if (bucketSizeLimit == Integer.MAX_VALUE) { tuple.put("totalRows", tuples.size()); } return tuple; } } private String getJsonFacetString( Bucket[] _buckets, Metric[] _metrics, FieldComparator[] _sorts, String _method, boolean _refine, int _limit) { StringBuilder buf = new StringBuilder(); appendJson(buf, _buckets, _metrics, _sorts, _limit, _method, _refine, 0); return "{" + buf.toString() + "}"; } private FieldComparator[] adjustSorts(Bucket[] _buckets, FieldComparator[] _sorts) throws IOException { if (_buckets.length == _sorts.length) { return _sorts; } else if (_sorts.length == 1) { FieldComparator[] adjustedSorts = new FieldComparator[_buckets.length]; if (_sorts[0].getLeftFieldName().contains("(")) { // It's a metric sort so apply the same sort criteria at each level. for (int i = 0; i < adjustedSorts.length; i++) { adjustedSorts[i] = _sorts[0]; } } else { // It's an index sort so apply an index sort at each level. for (int i = 0; i < adjustedSorts.length; i++) { adjustedSorts[i] = new FieldComparator(_buckets[i].toString(), _sorts[0].getOrder()); } } return adjustedSorts; } else { throw new IOException( "If multiple sorts are specified there must be a sort for each bucket."); } } private boolean resortNeeded(FieldComparator[] fieldComparators) { for (FieldComparator fieldComparator : fieldComparators) { if (fieldComparator.getLeftFieldName().contains("(")) { return true; } } return false; } private void appendJson( StringBuilder buf, Bucket[] _buckets, Metric[] _metrics, FieldComparator[] _sorts, int _limit, String method, boolean refine, int level) { buf.append('"'); buf.append(_buckets[level].toString()); buf.append('"'); buf.append(":{"); buf.append("\"type\":\"terms\""); buf.append(",\"field\":\"").append(_buckets[level].toString()).append('"'); buf.append(",\"limit\":").append(_limit); if (refine) { buf.append(",\"refine\":true"); } if (method != null) { buf.append(",\"method\":\"").append(method).append('"'); } String fsort = getFacetSort(_sorts[level].getLeftFieldName(), _metrics); buf.append(",\"sort\":{\"") .append(fsort) .append("\":\"") .append(_sorts[level].getOrder()) .append("\"}"); buf.append(",\"facet\":{"); int metricCount = 0; ++level; boolean comma = false; for (Metric metric : _metrics) { // Only compute the metric if it's a leaf node or if the branch level sort equals is the // metric String facetKey = "facet_" + metricCount; String identifier = metric.getIdentifier(); if (!identifier.startsWith("count(")) { if (comma) { buf.append(","); } if (level == _buckets.length || fsort.equals(facetKey)) { comma = true; if (identifier.startsWith("per(")) { buf.append("\"facet_") .append(metricCount) .append("\":\"") .append(identifier.replaceFirst("per", "percentile")) .append('"'); } else if (identifier.startsWith("std(")) { buf.append("\"facet_") .append(metricCount) .append("\":\"") .append(identifier.replaceFirst("std", "stddev")) .append('"'); } else if (identifier.startsWith("countDist(")) { buf.append("\"facet_") .append(metricCount) .append("\":\"") .append(identifier.replaceFirst("countDist", "unique")) .append('"'); } else { buf.append('"').append(facetKey).append("\":\"").append(identifier).append('"'); } } ++metricCount; } } if (level < _buckets.length) { if (metricCount > 0) { buf.append(","); } appendJson(buf, _buckets, _metrics, _sorts, _limit, method, refine, level); } buf.append("}}"); } private String getFacetSort(String id, Metric[] _metrics) { int index = 0; int metricCount = 0; for (Metric metric : _metrics) { if (metric.getIdentifier().startsWith("count(")) { if (id.startsWith("count(")) { return "count"; } ++index; } else { if (id.equals(_metrics[index].getIdentifier())) { return "facet_" + metricCount; } ++index; ++metricCount; } } return "index"; } private void getTuples(NamedList<?> response, Bucket[] buckets, Metric[] metrics) { Tuple tuple = new Tuple(); NamedList<?> facets = (NamedList<?>) response.get("facets"); fillTuples(0, tuples, tuple, facets, buckets, metrics); } private void fillTuples( int level, List<Tuple> tuples, Tuple currentTuple, NamedList<?> facets, Bucket[] _buckets, Metric[] _metrics) { String bucketName = _buckets[level].toString(); NamedList<?> nl = (NamedList<?>) facets.get(bucketName); if (nl == null) { return; } List<?> allBuckets = (List<?>) nl.get("buckets"); for (int b = 0; b < allBuckets.size(); b++) { NamedList<?> bucket = (NamedList<?>) allBuckets.get(b); Object val = bucket.get("val"); if (val instanceof Integer) { val = ((Integer) val).longValue(); // calcite currently expects Long values here } Tuple t = currentTuple.clone(); t.put(bucketName, val); int nextLevel = level + 1; if (nextLevel < _buckets.length) { fillTuples(nextLevel, tuples, t.clone(), bucket, _buckets, _metrics); } else { int m = 0; for (Metric metric : _metrics) { String identifier = metric.getIdentifier(); if (!identifier.startsWith("count(")) { Number d = ((Number) bucket.get("facet_" + m)); if (metric.outputLong) { if (d instanceof Long || d instanceof Integer) { t.put(identifier, d.longValue()); } else { t.put(identifier, Math.round(d.doubleValue())); } } else { t.put(identifier, d.doubleValue()); } ++m; } else { long l = ((Number) bucket.get("count")).longValue(); t.put("count(*)", l); } } tuples.add(t); } } } @Override public int getCost() { return 0; } @Override public StreamComparator getStreamSort() { if (bucketSorts.length > 1) { return new MultipleFieldComparator(bucketSorts); } else { return bucketSorts[0]; } } List<Metric> getMetrics() { return Arrays.asList(metrics); } @Override public TupleStream[] parallelize(List<String> partitions) throws IOException { final ModifiableSolrParams withoutTieredParam = new ModifiableSolrParams(params); withoutTieredParam.remove(TIERED_PARAM); // each individual facet request is not tiered TupleStream[] streams = new TupleStream[partitions.size()]; for (int p = 0; p < streams.length; p++) { FacetStream cloned = new FacetStream(); cloned.init( partitions.get(p), /* each collection */ withoutTieredParam, /* removes the tiered param */ buckets, bucketSorts, metrics, rows, offset, bucketSizeLimit, refine, method, serializeBucketSizeLimit, overfetch, zkHost); streams[p] = cloned; } return streams; } @Override public TupleStream getSortedRollupStream(ParallelListStream plist, Metric[] rollupMetrics) throws IOException { // using a hashRollup removes the need to sort the streams from the plist HashRollupStream rollup = new HashRollupStream(plist, buckets, rollupMetrics); SelectStream select = new SelectStream(rollup, getRollupSelectFields(rollupMetrics)); // the final stream must be sorted based on the original stream sort return new SortStream(select, getStreamSort()); } /** * The projection of dimensions and metrics from the rollup stream. * * @param rollupMetrics The metrics being rolled up. * @return A mapping of fields produced by the rollup stream to their output name. */ protected Map<String, String> getRollupSelectFields(Metric[] rollupMetrics) { Map<String, String> map = CollectionUtil.newHashMap(rollupMetrics.length * 2); for (Bucket b : buckets) { String key = b.toString(); map.put(key, key); } for (Metric m : rollupMetrics) { String[] cols = m.getColumns(); String col = cols != null && cols.length > 0 ? cols[0] : "*"; map.put(m.getIdentifier(), col); } return map; } }
googleapis/google-cloud-java
35,355
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/ListEntitiesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataplex/v1/metadata.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * List metadata entities response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEntitiesResponse} */ public final class ListEntitiesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.ListEntitiesResponse) ListEntitiesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListEntitiesResponse.newBuilder() to construct. private ListEntitiesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEntitiesResponse() { entities_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEntitiesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.MetadataProto .internal_static_google_cloud_dataplex_v1_ListEntitiesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.MetadataProto .internal_static_google_cloud_dataplex_v1_ListEntitiesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEntitiesResponse.class, com.google.cloud.dataplex.v1.ListEntitiesResponse.Builder.class); } public static final int ENTITIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dataplex.v1.Entity> entities_; /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dataplex.v1.Entity> getEntitiesList() { return entities_; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dataplex.v1.EntityOrBuilder> getEntitiesOrBuilderList() { return entities_; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ @java.lang.Override public int getEntitiesCount() { return entities_.size(); } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.Entity getEntities(int index) { return entities_.get(index); } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.EntityOrBuilder getEntitiesOrBuilder(int index) { return entities_.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 * remaining 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 * remaining 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 < entities_.size(); i++) { output.writeMessage(1, entities_.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 < entities_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entities_.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.dataplex.v1.ListEntitiesResponse)) { return super.equals(obj); } com.google.cloud.dataplex.v1.ListEntitiesResponse other = (com.google.cloud.dataplex.v1.ListEntitiesResponse) obj; if (!getEntitiesList().equals(other.getEntitiesList())) 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 (getEntitiesCount() > 0) { hash = (37 * hash) + ENTITIES_FIELD_NUMBER; hash = (53 * hash) + getEntitiesList().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.dataplex.v1.ListEntitiesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataplex.v1.ListEntitiesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * List metadata entities response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEntitiesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.ListEntitiesResponse) com.google.cloud.dataplex.v1.ListEntitiesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.MetadataProto .internal_static_google_cloud_dataplex_v1_ListEntitiesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.MetadataProto .internal_static_google_cloud_dataplex_v1_ListEntitiesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEntitiesResponse.class, com.google.cloud.dataplex.v1.ListEntitiesResponse.Builder.class); } // Construct using com.google.cloud.dataplex.v1.ListEntitiesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (entitiesBuilder_ == null) { entities_ = java.util.Collections.emptyList(); } else { entities_ = null; entitiesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.MetadataProto .internal_static_google_cloud_dataplex_v1_ListEntitiesResponse_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntitiesResponse getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.ListEntitiesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntitiesResponse build() { com.google.cloud.dataplex.v1.ListEntitiesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntitiesResponse buildPartial() { com.google.cloud.dataplex.v1.ListEntitiesResponse result = new com.google.cloud.dataplex.v1.ListEntitiesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dataplex.v1.ListEntitiesResponse result) { if (entitiesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { entities_ = java.util.Collections.unmodifiableList(entities_); bitField0_ = (bitField0_ & ~0x00000001); } result.entities_ = entities_; } else { result.entities_ = entitiesBuilder_.build(); } } private void buildPartial0(com.google.cloud.dataplex.v1.ListEntitiesResponse 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.dataplex.v1.ListEntitiesResponse) { return mergeFrom((com.google.cloud.dataplex.v1.ListEntitiesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.ListEntitiesResponse other) { if (other == com.google.cloud.dataplex.v1.ListEntitiesResponse.getDefaultInstance()) return this; if (entitiesBuilder_ == null) { if (!other.entities_.isEmpty()) { if (entities_.isEmpty()) { entities_ = other.entities_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEntitiesIsMutable(); entities_.addAll(other.entities_); } onChanged(); } } else { if (!other.entities_.isEmpty()) { if (entitiesBuilder_.isEmpty()) { entitiesBuilder_.dispose(); entitiesBuilder_ = null; entities_ = other.entities_; bitField0_ = (bitField0_ & ~0x00000001); entitiesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntitiesFieldBuilder() : null; } else { entitiesBuilder_.addAllMessages(other.entities_); } } } 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.dataplex.v1.Entity m = input.readMessage( com.google.cloud.dataplex.v1.Entity.parser(), extensionRegistry); if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(m); } else { entitiesBuilder_.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.dataplex.v1.Entity> entities_ = java.util.Collections.emptyList(); private void ensureEntitiesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { entities_ = new java.util.ArrayList<com.google.cloud.dataplex.v1.Entity>(entities_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entity, com.google.cloud.dataplex.v1.Entity.Builder, com.google.cloud.dataplex.v1.EntityOrBuilder> entitiesBuilder_; /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Entity> getEntitiesList() { if (entitiesBuilder_ == null) { return java.util.Collections.unmodifiableList(entities_); } else { return entitiesBuilder_.getMessageList(); } } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public int getEntitiesCount() { if (entitiesBuilder_ == null) { return entities_.size(); } else { return entitiesBuilder_.getCount(); } } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public com.google.cloud.dataplex.v1.Entity getEntities(int index) { if (entitiesBuilder_ == null) { return entities_.get(index); } else { return entitiesBuilder_.getMessage(index); } } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder setEntities(int index, com.google.cloud.dataplex.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.set(index, value); onChanged(); } else { entitiesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder setEntities( int index, com.google.cloud.dataplex.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.set(index, builderForValue.build()); onChanged(); } else { entitiesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder addEntities(com.google.cloud.dataplex.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.add(value); onChanged(); } else { entitiesBuilder_.addMessage(value); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder addEntities(int index, com.google.cloud.dataplex.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.add(index, value); onChanged(); } else { entitiesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder addEntities(com.google.cloud.dataplex.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(builderForValue.build()); onChanged(); } else { entitiesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder addEntities( int index, com.google.cloud.dataplex.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(index, builderForValue.build()); onChanged(); } else { entitiesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder addAllEntities( java.lang.Iterable<? extends com.google.cloud.dataplex.v1.Entity> values) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entities_); onChanged(); } else { entitiesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder clearEntities() { if (entitiesBuilder_ == null) { entities_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { entitiesBuilder_.clear(); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public Builder removeEntities(int index) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.remove(index); onChanged(); } else { entitiesBuilder_.remove(index); } return this; } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public com.google.cloud.dataplex.v1.Entity.Builder getEntitiesBuilder(int index) { return getEntitiesFieldBuilder().getBuilder(index); } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public com.google.cloud.dataplex.v1.EntityOrBuilder getEntitiesOrBuilder(int index) { if (entitiesBuilder_ == null) { return entities_.get(index); } else { return entitiesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public java.util.List<? extends com.google.cloud.dataplex.v1.EntityOrBuilder> getEntitiesOrBuilderList() { if (entitiesBuilder_ != null) { return entitiesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entities_); } } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public com.google.cloud.dataplex.v1.Entity.Builder addEntitiesBuilder() { return getEntitiesFieldBuilder() .addBuilder(com.google.cloud.dataplex.v1.Entity.getDefaultInstance()); } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public com.google.cloud.dataplex.v1.Entity.Builder addEntitiesBuilder(int index) { return getEntitiesFieldBuilder() .addBuilder(index, com.google.cloud.dataplex.v1.Entity.getDefaultInstance()); } /** * * * <pre> * Entities in the specified parent zone. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Entity entities = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Entity.Builder> getEntitiesBuilderList() { return getEntitiesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entity, com.google.cloud.dataplex.v1.Entity.Builder, com.google.cloud.dataplex.v1.EntityOrBuilder> getEntitiesFieldBuilder() { if (entitiesBuilder_ == null) { entitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Entity, com.google.cloud.dataplex.v1.Entity.Builder, com.google.cloud.dataplex.v1.EntityOrBuilder>( entities_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); entities_ = null; } return entitiesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no * remaining 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 * remaining 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 * remaining 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 * remaining 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 * remaining 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.dataplex.v1.ListEntitiesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.ListEntitiesResponse) private static final com.google.cloud.dataplex.v1.ListEntitiesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.ListEntitiesResponse(); } public static com.google.cloud.dataplex.v1.ListEntitiesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEntitiesResponse> PARSER = new com.google.protobuf.AbstractParser<ListEntitiesResponse>() { @java.lang.Override public ListEntitiesResponse 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<ListEntitiesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEntitiesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEntitiesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,458
java-alloydb/proto-google-cloud-alloydb-v1alpha/src/main/java/com/google/cloud/alloydb/v1alpha/SwitchoverClusterRequest.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/v1alpha/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.alloydb.v1alpha; /** * * * <pre> * Message for switching over to a cluster * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.SwitchoverClusterRequest} */ public final class SwitchoverClusterRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) SwitchoverClusterRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SwitchoverClusterRequest.newBuilder() to construct. private SwitchoverClusterRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SwitchoverClusterRequest() { name_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SwitchoverClusterRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_SwitchoverClusterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_SwitchoverClusterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.class, com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest)) { return super.equals(obj); } com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest other = (com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) obj; if (!getName().equals(other.getName())) return false; if (!getRequestId().equals(other.getRequestId())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest 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.v1alpha.SwitchoverClusterRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest 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.v1alpha.SwitchoverClusterRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest 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.v1alpha.SwitchoverClusterRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest 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.v1alpha.SwitchoverClusterRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest 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.v1alpha.SwitchoverClusterRequest 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 switching over to a cluster * </pre> * * Protobuf type {@code google.cloud.alloydb.v1alpha.SwitchoverClusterRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_SwitchoverClusterRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_SwitchoverClusterRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.class, com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.Builder.class); } // Construct using com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; requestId_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.alloydb.v1alpha.ServiceProto .internal_static_google_cloud_alloydb_v1alpha_SwitchoverClusterRequest_descriptor; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest getDefaultInstanceForType() { return com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest build() { com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest buildPartial() { com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest result = new com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.requestId_ = requestId_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) { return mergeFrom((com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest other) { if (other == com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getRequestId().isEmpty()) { requestId_ = other.requestId_; bitField0_ |= 0x00000002; onChanged(); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { requestId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of the resource. For the required format, see the * comment on the Cluster.name field * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. An optional request ID to identify requests. Specify a unique * request ID so that if you must retry your request, the server ignores the * request if it has already been completed. The server guarantees that for at * least 60 minutes since the first request. * * 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 the original operation with the same request ID * was received, and if so, ignores the second request. This prevents * clients from accidentally creating duplicate commitments. * * The request ID must be a valid UUID with the exception that zero UUID is * not supported (00000000-0000-0000-0000-000000000000). * </pre> * * <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private boolean validateOnly_; /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. If set, performs request validation, for example, permission * checks and any other type of validation, but does not actually execute the * create request. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) } // @@protoc_insertion_point(class_scope:google.cloud.alloydb.v1alpha.SwitchoverClusterRequest) private static final com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest(); } public static com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SwitchoverClusterRequest> PARSER = new com.google.protobuf.AbstractParser<SwitchoverClusterRequest>() { @java.lang.Override public SwitchoverClusterRequest 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<SwitchoverClusterRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SwitchoverClusterRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.alloydb.v1alpha.SwitchoverClusterRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,441
java-datacatalog/proto-google-cloud-datacatalog-v1beta1/src/main/java/com/google/cloud/datacatalog/v1beta1/UpdateTaxonomyRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datacatalog/v1beta1/policytagmanager.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datacatalog.v1beta1; /** * * * <pre> * Request message for * [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest} */ public final class UpdateTaxonomyRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest) UpdateTaxonomyRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateTaxonomyRequest.newBuilder() to construct. private UpdateTaxonomyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateTaxonomyRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateTaxonomyRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1beta1.PolicyTagManagerProto .internal_static_google_cloud_datacatalog_v1beta1_UpdateTaxonomyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1beta1.PolicyTagManagerProto .internal_static_google_cloud_datacatalog_v1beta1_UpdateTaxonomyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.class, com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.Builder.class); } private int bitField0_; public static final int TAXONOMY_FIELD_NUMBER = 1; private com.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy_; /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> * * @return Whether the taxonomy field is set. */ @java.lang.Override public boolean hasTaxonomy() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> * * @return The taxonomy. */ @java.lang.Override public com.google.cloud.datacatalog.v1beta1.Taxonomy getTaxonomy() { return taxonomy_ == null ? com.google.cloud.datacatalog.v1beta1.Taxonomy.getDefaultInstance() : taxonomy_; } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ @java.lang.Override public com.google.cloud.datacatalog.v1beta1.TaxonomyOrBuilder getTaxonomyOrBuilder() { return taxonomy_ == null ? com.google.cloud.datacatalog.v1beta1.Taxonomy.getDefaultInstance() : taxonomy_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </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, getTaxonomy()); } 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, getTaxonomy()); } 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.datacatalog.v1beta1.UpdateTaxonomyRequest)) { return super.equals(obj); } com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest other = (com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest) obj; if (hasTaxonomy() != other.hasTaxonomy()) return false; if (hasTaxonomy()) { if (!getTaxonomy().equals(other.getTaxonomy())) 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 (hasTaxonomy()) { hash = (37 * hash) + TAXONOMY_FIELD_NUMBER; hash = (53 * hash) + getTaxonomy().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.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest 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 * [UpdateTaxonomy][google.cloud.datacatalog.v1beta1.PolicyTagManager.UpdateTaxonomy]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest) com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1beta1.PolicyTagManagerProto .internal_static_google_cloud_datacatalog_v1beta1_UpdateTaxonomyRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1beta1.PolicyTagManagerProto .internal_static_google_cloud_datacatalog_v1beta1_UpdateTaxonomyRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.class, com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.Builder.class); } // Construct using com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTaxonomyFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; taxonomy_ = null; if (taxonomyBuilder_ != null) { taxonomyBuilder_.dispose(); taxonomyBuilder_ = 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.datacatalog.v1beta1.PolicyTagManagerProto .internal_static_google_cloud_datacatalog_v1beta1_UpdateTaxonomyRequest_descriptor; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest getDefaultInstanceForType() { return com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest build() { com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest buildPartial() { com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest result = new com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.taxonomy_ = taxonomyBuilder_ == null ? taxonomy_ : taxonomyBuilder_.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.datacatalog.v1beta1.UpdateTaxonomyRequest) { return mergeFrom((com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest other) { if (other == com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest.getDefaultInstance()) return this; if (other.hasTaxonomy()) { mergeTaxonomy(other.getTaxonomy()); } 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(getTaxonomyFieldBuilder().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.datacatalog.v1beta1.Taxonomy taxonomy_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Taxonomy, com.google.cloud.datacatalog.v1beta1.Taxonomy.Builder, com.google.cloud.datacatalog.v1beta1.TaxonomyOrBuilder> taxonomyBuilder_; /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> * * @return Whether the taxonomy field is set. */ public boolean hasTaxonomy() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> * * @return The taxonomy. */ public com.google.cloud.datacatalog.v1beta1.Taxonomy getTaxonomy() { if (taxonomyBuilder_ == null) { return taxonomy_ == null ? com.google.cloud.datacatalog.v1beta1.Taxonomy.getDefaultInstance() : taxonomy_; } else { return taxonomyBuilder_.getMessage(); } } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public Builder setTaxonomy(com.google.cloud.datacatalog.v1beta1.Taxonomy value) { if (taxonomyBuilder_ == null) { if (value == null) { throw new NullPointerException(); } taxonomy_ = value; } else { taxonomyBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public Builder setTaxonomy( com.google.cloud.datacatalog.v1beta1.Taxonomy.Builder builderForValue) { if (taxonomyBuilder_ == null) { taxonomy_ = builderForValue.build(); } else { taxonomyBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public Builder mergeTaxonomy(com.google.cloud.datacatalog.v1beta1.Taxonomy value) { if (taxonomyBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && taxonomy_ != null && taxonomy_ != com.google.cloud.datacatalog.v1beta1.Taxonomy.getDefaultInstance()) { getTaxonomyBuilder().mergeFrom(value); } else { taxonomy_ = value; } } else { taxonomyBuilder_.mergeFrom(value); } if (taxonomy_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public Builder clearTaxonomy() { bitField0_ = (bitField0_ & ~0x00000001); taxonomy_ = null; if (taxonomyBuilder_ != null) { taxonomyBuilder_.dispose(); taxonomyBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public com.google.cloud.datacatalog.v1beta1.Taxonomy.Builder getTaxonomyBuilder() { bitField0_ |= 0x00000001; onChanged(); return getTaxonomyFieldBuilder().getBuilder(); } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ public com.google.cloud.datacatalog.v1beta1.TaxonomyOrBuilder getTaxonomyOrBuilder() { if (taxonomyBuilder_ != null) { return taxonomyBuilder_.getMessageOrBuilder(); } else { return taxonomy_ == null ? com.google.cloud.datacatalog.v1beta1.Taxonomy.getDefaultInstance() : taxonomy_; } } /** * * * <pre> * The taxonomy to update. Only description, display_name, and activated * policy types can be updated. * </pre> * * <code>.google.cloud.datacatalog.v1beta1.Taxonomy taxonomy = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Taxonomy, com.google.cloud.datacatalog.v1beta1.Taxonomy.Builder, com.google.cloud.datacatalog.v1beta1.TaxonomyOrBuilder> getTaxonomyFieldBuilder() { if (taxonomyBuilder_ == null) { taxonomyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.datacatalog.v1beta1.Taxonomy, com.google.cloud.datacatalog.v1beta1.Taxonomy.Builder, com.google.cloud.datacatalog.v1beta1.TaxonomyOrBuilder>( getTaxonomy(), getParentForChildren(), isClean()); taxonomy_ = null; } return taxonomyBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * The update mask applies to the resource. For the `FieldMask` definition, * see * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * If not set, defaults to all of the fields that are allowed to update. * </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.datacatalog.v1beta1.UpdateTaxonomyRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest) private static final com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest(); } public static com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateTaxonomyRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateTaxonomyRequest>() { @java.lang.Override public UpdateTaxonomyRequest 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<UpdateTaxonomyRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateTaxonomyRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datacatalog.v1beta1.UpdateTaxonomyRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,372
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/UpdateContentRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataplex/v1/content.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * Update content request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateContentRequest} */ public final class UpdateContentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.UpdateContentRequest) UpdateContentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateContentRequest.newBuilder() to construct. private UpdateContentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateContentRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateContentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.ContentProto .internal_static_google_cloud_dataplex_v1_UpdateContentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.ContentProto .internal_static_google_cloud_dataplex_v1_UpdateContentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateContentRequest.class, com.google.cloud.dataplex.v1.UpdateContentRequest.Builder.class); } private int bitField0_; public static final int UPDATE_MASK_FIELD_NUMBER = 1; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int CONTENT_FIELD_NUMBER = 2; private com.google.cloud.dataplex.v1.Content content_; /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code>.google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the content field is set. */ @java.lang.Override public boolean hasContent() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code>.google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The content. */ @java.lang.Override public com.google.cloud.dataplex.v1.Content getContent() { return content_ == null ? com.google.cloud.dataplex.v1.Content.getDefaultInstance() : content_; } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code>.google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dataplex.v1.ContentOrBuilder getContentOrBuilder() { return content_ == null ? com.google.cloud.dataplex.v1.Content.getDefaultInstance() : content_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getContent()); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getUpdateMask()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getContent()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dataplex.v1.UpdateContentRequest)) { return super.equals(obj); } com.google.cloud.dataplex.v1.UpdateContentRequest other = (com.google.cloud.dataplex.v1.UpdateContentRequest) obj; if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (hasContent() != other.hasContent()) return false; if (hasContent()) { if (!getContent().equals(other.getContent())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } if (hasContent()) { hash = (37 * hash) + CONTENT_FIELD_NUMBER; hash = (53 * hash) + getContent().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.UpdateContentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.dataplex.v1.UpdateContentRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Update content request. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.UpdateContentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.UpdateContentRequest) com.google.cloud.dataplex.v1.UpdateContentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.ContentProto .internal_static_google_cloud_dataplex_v1_UpdateContentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.ContentProto .internal_static_google_cloud_dataplex_v1_UpdateContentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.UpdateContentRequest.class, com.google.cloud.dataplex.v1.UpdateContentRequest.Builder.class); } // Construct using com.google.cloud.dataplex.v1.UpdateContentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getUpdateMaskFieldBuilder(); getContentFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } content_ = null; if (contentBuilder_ != null) { contentBuilder_.dispose(); contentBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.ContentProto .internal_static_google_cloud_dataplex_v1_UpdateContentRequest_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateContentRequest getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.UpdateContentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateContentRequest build() { com.google.cloud.dataplex.v1.UpdateContentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateContentRequest buildPartial() { com.google.cloud.dataplex.v1.UpdateContentRequest result = new com.google.cloud.dataplex.v1.UpdateContentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.dataplex.v1.UpdateContentRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.content_ = contentBuilder_ == null ? content_ : contentBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dataplex.v1.UpdateContentRequest) { return mergeFrom((com.google.cloud.dataplex.v1.UpdateContentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.UpdateContentRequest other) { if (other == com.google.cloud.dataplex.v1.UpdateContentRequest.getDefaultInstance()) return this; if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.hasContent()) { mergeContent(other.getContent()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getContentFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000001); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000001; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. Mask of fields to update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private com.google.cloud.dataplex.v1.Content content_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.Content, com.google.cloud.dataplex.v1.Content.Builder, com.google.cloud.dataplex.v1.ContentOrBuilder> contentBuilder_; /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the content field is set. */ public boolean hasContent() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The content. */ public com.google.cloud.dataplex.v1.Content getContent() { if (contentBuilder_ == null) { return content_ == null ? com.google.cloud.dataplex.v1.Content.getDefaultInstance() : content_; } else { return contentBuilder_.getMessage(); } } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setContent(com.google.cloud.dataplex.v1.Content value) { if (contentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } content_ = value; } else { contentBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setContent(com.google.cloud.dataplex.v1.Content.Builder builderForValue) { if (contentBuilder_ == null) { content_ = builderForValue.build(); } else { contentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeContent(com.google.cloud.dataplex.v1.Content value) { if (contentBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && content_ != null && content_ != com.google.cloud.dataplex.v1.Content.getDefaultInstance()) { getContentBuilder().mergeFrom(value); } else { content_ = value; } } else { contentBuilder_.mergeFrom(value); } if (content_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearContent() { bitField0_ = (bitField0_ & ~0x00000002); content_ = null; if (contentBuilder_ != null) { contentBuilder_.dispose(); contentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.Content.Builder getContentBuilder() { bitField0_ |= 0x00000002; onChanged(); return getContentFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dataplex.v1.ContentOrBuilder getContentOrBuilder() { if (contentBuilder_ != null) { return contentBuilder_.getMessageOrBuilder(); } else { return content_ == null ? com.google.cloud.dataplex.v1.Content.getDefaultInstance() : content_; } } /** * * * <pre> * Required. Update description. * Only fields specified in `update_mask` are updated. * </pre> * * <code> * .google.cloud.dataplex.v1.Content content = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.Content, com.google.cloud.dataplex.v1.Content.Builder, com.google.cloud.dataplex.v1.ContentOrBuilder> getContentFieldBuilder() { if (contentBuilder_ == null) { contentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dataplex.v1.Content, com.google.cloud.dataplex.v1.Content.Builder, com.google.cloud.dataplex.v1.ContentOrBuilder>( getContent(), getParentForChildren(), isClean()); content_ = null; } return contentBuilder_; } private boolean validateOnly_; /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Only validate the request, but do not perform mutations. * The default is false. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataplex.v1.UpdateContentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.UpdateContentRequest) private static final com.google.cloud.dataplex.v1.UpdateContentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.UpdateContentRequest(); } public static com.google.cloud.dataplex.v1.UpdateContentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateContentRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateContentRequest>() { @java.lang.Override public UpdateContentRequest 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<UpdateContentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateContentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.UpdateContentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hive
35,462
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/PartitionWithoutSD.java
/** * Autogenerated by Thrift Compiler (0.16.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) @javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.16.0)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class PartitionWithoutSD implements org.apache.thrift.TBase<PartitionWithoutSD, PartitionWithoutSD._Fields>, java.io.Serializable, Cloneable, Comparable<PartitionWithoutSD> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("PartitionWithoutSD"); private static final org.apache.thrift.protocol.TField VALUES_FIELD_DESC = new org.apache.thrift.protocol.TField("values", org.apache.thrift.protocol.TType.LIST, (short)1); private static final org.apache.thrift.protocol.TField CREATE_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("createTime", org.apache.thrift.protocol.TType.I32, (short)2); private static final org.apache.thrift.protocol.TField LAST_ACCESS_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("lastAccessTime", org.apache.thrift.protocol.TType.I32, (short)3); private static final org.apache.thrift.protocol.TField RELATIVE_PATH_FIELD_DESC = new org.apache.thrift.protocol.TField("relativePath", org.apache.thrift.protocol.TType.STRING, (short)4); private static final org.apache.thrift.protocol.TField PARAMETERS_FIELD_DESC = new org.apache.thrift.protocol.TField("parameters", org.apache.thrift.protocol.TType.MAP, (short)5); private static final org.apache.thrift.protocol.TField PRIVILEGES_FIELD_DESC = new org.apache.thrift.protocol.TField("privileges", org.apache.thrift.protocol.TType.STRUCT, (short)6); private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new PartitionWithoutSDStandardSchemeFactory(); private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new PartitionWithoutSDTupleSchemeFactory(); private @org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> values; // required private int createTime; // required private int lastAccessTime; // required private @org.apache.thrift.annotation.Nullable java.lang.String relativePath; // required private @org.apache.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.String> parameters; // required private @org.apache.thrift.annotation.Nullable PrincipalPrivilegeSet privileges; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { VALUES((short)1, "values"), CREATE_TIME((short)2, "createTime"), LAST_ACCESS_TIME((short)3, "lastAccessTime"), RELATIVE_PATH((short)4, "relativePath"), PARAMETERS((short)5, "parameters"), PRIVILEGES((short)6, "privileges"); private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>(); static { for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // VALUES return VALUES; case 2: // CREATE_TIME return CREATE_TIME; case 3: // LAST_ACCESS_TIME return LAST_ACCESS_TIME; case 4: // RELATIVE_PATH return RELATIVE_PATH; case 5: // PARAMETERS return PARAMETERS; case 6: // PRIVILEGES return PRIVILEGES; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ @org.apache.thrift.annotation.Nullable public static _Fields findByName(java.lang.String name) { return byName.get(name); } private final short _thriftId; private final java.lang.String _fieldName; _Fields(short thriftId, java.lang.String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public java.lang.String getFieldName() { return _fieldName; } } // isset id assignments private static final int __CREATETIME_ISSET_ID = 0; private static final int __LASTACCESSTIME_ISSET_ID = 1; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.PRIVILEGES}; public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.VALUES, new org.apache.thrift.meta_data.FieldMetaData("values", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.CREATE_TIME, new org.apache.thrift.meta_data.FieldMetaData("createTime", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.LAST_ACCESS_TIME, new org.apache.thrift.meta_data.FieldMetaData("lastAccessTime", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.RELATIVE_PATH, new org.apache.thrift.meta_data.FieldMetaData("relativePath", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PARAMETERS, new org.apache.thrift.meta_data.FieldMetaData("parameters", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING), new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)))); tmpMap.put(_Fields.PRIVILEGES, new org.apache.thrift.meta_data.FieldMetaData("privileges", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, PrincipalPrivilegeSet.class))); metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(PartitionWithoutSD.class, metaDataMap); } public PartitionWithoutSD() { } public PartitionWithoutSD( java.util.List<java.lang.String> values, int createTime, int lastAccessTime, java.lang.String relativePath, java.util.Map<java.lang.String,java.lang.String> parameters) { this(); this.values = values; this.createTime = createTime; setCreateTimeIsSet(true); this.lastAccessTime = lastAccessTime; setLastAccessTimeIsSet(true); this.relativePath = relativePath; this.parameters = parameters; } /** * Performs a deep copy on <i>other</i>. */ public PartitionWithoutSD(PartitionWithoutSD other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetValues()) { java.util.List<java.lang.String> __this__values = new java.util.ArrayList<java.lang.String>(other.values); this.values = __this__values; } this.createTime = other.createTime; this.lastAccessTime = other.lastAccessTime; if (other.isSetRelativePath()) { this.relativePath = other.relativePath; } if (other.isSetParameters()) { java.util.Map<java.lang.String,java.lang.String> __this__parameters = new java.util.HashMap<java.lang.String,java.lang.String>(other.parameters); this.parameters = __this__parameters; } if (other.isSetPrivileges()) { this.privileges = new PrincipalPrivilegeSet(other.privileges); } } public PartitionWithoutSD deepCopy() { return new PartitionWithoutSD(this); } @Override public void clear() { this.values = null; setCreateTimeIsSet(false); this.createTime = 0; setLastAccessTimeIsSet(false); this.lastAccessTime = 0; this.relativePath = null; this.parameters = null; this.privileges = null; } public int getValuesSize() { return (this.values == null) ? 0 : this.values.size(); } @org.apache.thrift.annotation.Nullable public java.util.Iterator<java.lang.String> getValuesIterator() { return (this.values == null) ? null : this.values.iterator(); } public void addToValues(java.lang.String elem) { if (this.values == null) { this.values = new java.util.ArrayList<java.lang.String>(); } this.values.add(elem); } @org.apache.thrift.annotation.Nullable public java.util.List<java.lang.String> getValues() { return this.values; } public void setValues(@org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> values) { this.values = values; } public void unsetValues() { this.values = null; } /** Returns true if field values is set (has been assigned a value) and false otherwise */ public boolean isSetValues() { return this.values != null; } public void setValuesIsSet(boolean value) { if (!value) { this.values = null; } } public int getCreateTime() { return this.createTime; } public void setCreateTime(int createTime) { this.createTime = createTime; setCreateTimeIsSet(true); } public void unsetCreateTime() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CREATETIME_ISSET_ID); } /** Returns true if field createTime is set (has been assigned a value) and false otherwise */ public boolean isSetCreateTime() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CREATETIME_ISSET_ID); } public void setCreateTimeIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CREATETIME_ISSET_ID, value); } public int getLastAccessTime() { return this.lastAccessTime; } public void setLastAccessTime(int lastAccessTime) { this.lastAccessTime = lastAccessTime; setLastAccessTimeIsSet(true); } public void unsetLastAccessTime() { __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __LASTACCESSTIME_ISSET_ID); } /** Returns true if field lastAccessTime is set (has been assigned a value) and false otherwise */ public boolean isSetLastAccessTime() { return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __LASTACCESSTIME_ISSET_ID); } public void setLastAccessTimeIsSet(boolean value) { __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __LASTACCESSTIME_ISSET_ID, value); } @org.apache.thrift.annotation.Nullable public java.lang.String getRelativePath() { return this.relativePath; } public void setRelativePath(@org.apache.thrift.annotation.Nullable java.lang.String relativePath) { this.relativePath = relativePath; } public void unsetRelativePath() { this.relativePath = null; } /** Returns true if field relativePath is set (has been assigned a value) and false otherwise */ public boolean isSetRelativePath() { return this.relativePath != null; } public void setRelativePathIsSet(boolean value) { if (!value) { this.relativePath = null; } } public int getParametersSize() { return (this.parameters == null) ? 0 : this.parameters.size(); } public void putToParameters(java.lang.String key, java.lang.String val) { if (this.parameters == null) { this.parameters = new java.util.HashMap<java.lang.String,java.lang.String>(); } this.parameters.put(key, val); } @org.apache.thrift.annotation.Nullable public java.util.Map<java.lang.String,java.lang.String> getParameters() { return this.parameters; } public void setParameters(@org.apache.thrift.annotation.Nullable java.util.Map<java.lang.String,java.lang.String> parameters) { this.parameters = parameters; } public void unsetParameters() { this.parameters = null; } /** Returns true if field parameters is set (has been assigned a value) and false otherwise */ public boolean isSetParameters() { return this.parameters != null; } public void setParametersIsSet(boolean value) { if (!value) { this.parameters = null; } } @org.apache.thrift.annotation.Nullable public PrincipalPrivilegeSet getPrivileges() { return this.privileges; } public void setPrivileges(@org.apache.thrift.annotation.Nullable PrincipalPrivilegeSet privileges) { this.privileges = privileges; } public void unsetPrivileges() { this.privileges = null; } /** Returns true if field privileges is set (has been assigned a value) and false otherwise */ public boolean isSetPrivileges() { return this.privileges != null; } public void setPrivilegesIsSet(boolean value) { if (!value) { this.privileges = null; } } public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) { switch (field) { case VALUES: if (value == null) { unsetValues(); } else { setValues((java.util.List<java.lang.String>)value); } break; case CREATE_TIME: if (value == null) { unsetCreateTime(); } else { setCreateTime((java.lang.Integer)value); } break; case LAST_ACCESS_TIME: if (value == null) { unsetLastAccessTime(); } else { setLastAccessTime((java.lang.Integer)value); } break; case RELATIVE_PATH: if (value == null) { unsetRelativePath(); } else { setRelativePath((java.lang.String)value); } break; case PARAMETERS: if (value == null) { unsetParameters(); } else { setParameters((java.util.Map<java.lang.String,java.lang.String>)value); } break; case PRIVILEGES: if (value == null) { unsetPrivileges(); } else { setPrivileges((PrincipalPrivilegeSet)value); } break; } } @org.apache.thrift.annotation.Nullable public java.lang.Object getFieldValue(_Fields field) { switch (field) { case VALUES: return getValues(); case CREATE_TIME: return getCreateTime(); case LAST_ACCESS_TIME: return getLastAccessTime(); case RELATIVE_PATH: return getRelativePath(); case PARAMETERS: return getParameters(); case PRIVILEGES: return getPrivileges(); } throw new java.lang.IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new java.lang.IllegalArgumentException(); } switch (field) { case VALUES: return isSetValues(); case CREATE_TIME: return isSetCreateTime(); case LAST_ACCESS_TIME: return isSetLastAccessTime(); case RELATIVE_PATH: return isSetRelativePath(); case PARAMETERS: return isSetParameters(); case PRIVILEGES: return isSetPrivileges(); } throw new java.lang.IllegalStateException(); } @Override public boolean equals(java.lang.Object that) { if (that instanceof PartitionWithoutSD) return this.equals((PartitionWithoutSD)that); return false; } public boolean equals(PartitionWithoutSD that) { if (that == null) return false; if (this == that) return true; boolean this_present_values = true && this.isSetValues(); boolean that_present_values = true && that.isSetValues(); if (this_present_values || that_present_values) { if (!(this_present_values && that_present_values)) return false; if (!this.values.equals(that.values)) return false; } boolean this_present_createTime = true; boolean that_present_createTime = true; if (this_present_createTime || that_present_createTime) { if (!(this_present_createTime && that_present_createTime)) return false; if (this.createTime != that.createTime) return false; } boolean this_present_lastAccessTime = true; boolean that_present_lastAccessTime = true; if (this_present_lastAccessTime || that_present_lastAccessTime) { if (!(this_present_lastAccessTime && that_present_lastAccessTime)) return false; if (this.lastAccessTime != that.lastAccessTime) return false; } boolean this_present_relativePath = true && this.isSetRelativePath(); boolean that_present_relativePath = true && that.isSetRelativePath(); if (this_present_relativePath || that_present_relativePath) { if (!(this_present_relativePath && that_present_relativePath)) return false; if (!this.relativePath.equals(that.relativePath)) return false; } boolean this_present_parameters = true && this.isSetParameters(); boolean that_present_parameters = true && that.isSetParameters(); if (this_present_parameters || that_present_parameters) { if (!(this_present_parameters && that_present_parameters)) return false; if (!this.parameters.equals(that.parameters)) return false; } boolean this_present_privileges = true && this.isSetPrivileges(); boolean that_present_privileges = true && that.isSetPrivileges(); if (this_present_privileges || that_present_privileges) { if (!(this_present_privileges && that_present_privileges)) return false; if (!this.privileges.equals(that.privileges)) return false; } return true; } @Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 8191 + ((isSetValues()) ? 131071 : 524287); if (isSetValues()) hashCode = hashCode * 8191 + values.hashCode(); hashCode = hashCode * 8191 + createTime; hashCode = hashCode * 8191 + lastAccessTime; hashCode = hashCode * 8191 + ((isSetRelativePath()) ? 131071 : 524287); if (isSetRelativePath()) hashCode = hashCode * 8191 + relativePath.hashCode(); hashCode = hashCode * 8191 + ((isSetParameters()) ? 131071 : 524287); if (isSetParameters()) hashCode = hashCode * 8191 + parameters.hashCode(); hashCode = hashCode * 8191 + ((isSetPrivileges()) ? 131071 : 524287); if (isSetPrivileges()) hashCode = hashCode * 8191 + privileges.hashCode(); return hashCode; } @Override public int compareTo(PartitionWithoutSD other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = java.lang.Boolean.compare(isSetValues(), other.isSetValues()); if (lastComparison != 0) { return lastComparison; } if (isSetValues()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.values, other.values); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetCreateTime(), other.isSetCreateTime()); if (lastComparison != 0) { return lastComparison; } if (isSetCreateTime()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.createTime, other.createTime); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetLastAccessTime(), other.isSetLastAccessTime()); if (lastComparison != 0) { return lastComparison; } if (isSetLastAccessTime()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.lastAccessTime, other.lastAccessTime); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetRelativePath(), other.isSetRelativePath()); if (lastComparison != 0) { return lastComparison; } if (isSetRelativePath()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.relativePath, other.relativePath); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetParameters(), other.isSetParameters()); if (lastComparison != 0) { return lastComparison; } if (isSetParameters()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.parameters, other.parameters); if (lastComparison != 0) { return lastComparison; } } lastComparison = java.lang.Boolean.compare(isSetPrivileges(), other.isSetPrivileges()); if (lastComparison != 0) { return lastComparison; } if (isSetPrivileges()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.privileges, other.privileges); if (lastComparison != 0) { return lastComparison; } } return 0; } @org.apache.thrift.annotation.Nullable public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { scheme(iprot).read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { scheme(oprot).write(oprot, this); } @Override public java.lang.String toString() { java.lang.StringBuilder sb = new java.lang.StringBuilder("PartitionWithoutSD("); boolean first = true; sb.append("values:"); if (this.values == null) { sb.append("null"); } else { sb.append(this.values); } first = false; if (!first) sb.append(", "); sb.append("createTime:"); sb.append(this.createTime); first = false; if (!first) sb.append(", "); sb.append("lastAccessTime:"); sb.append(this.lastAccessTime); first = false; if (!first) sb.append(", "); sb.append("relativePath:"); if (this.relativePath == null) { sb.append("null"); } else { sb.append(this.relativePath); } first = false; if (!first) sb.append(", "); sb.append("parameters:"); if (this.parameters == null) { sb.append("null"); } else { sb.append(this.parameters); } first = false; if (isSetPrivileges()) { if (!first) sb.append(", "); sb.append("privileges:"); if (this.privileges == null) { sb.append("null"); } else { sb.append(this.privileges); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (privileges != null) { privileges.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class PartitionWithoutSDStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public PartitionWithoutSDStandardScheme getScheme() { return new PartitionWithoutSDStandardScheme(); } } private static class PartitionWithoutSDStandardScheme extends org.apache.thrift.scheme.StandardScheme<PartitionWithoutSD> { public void read(org.apache.thrift.protocol.TProtocol iprot, PartitionWithoutSD struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // VALUES if (schemeField.type == org.apache.thrift.protocol.TType.LIST) { { org.apache.thrift.protocol.TList _list412 = iprot.readListBegin(); struct.values = new java.util.ArrayList<java.lang.String>(_list412.size); @org.apache.thrift.annotation.Nullable java.lang.String _elem413; for (int _i414 = 0; _i414 < _list412.size; ++_i414) { _elem413 = iprot.readString(); struct.values.add(_elem413); } iprot.readListEnd(); } struct.setValuesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // CREATE_TIME if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.createTime = iprot.readI32(); struct.setCreateTimeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // LAST_ACCESS_TIME if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.lastAccessTime = iprot.readI32(); struct.setLastAccessTimeIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // RELATIVE_PATH if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.relativePath = iprot.readString(); struct.setRelativePathIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // PARAMETERS if (schemeField.type == org.apache.thrift.protocol.TType.MAP) { { org.apache.thrift.protocol.TMap _map415 = iprot.readMapBegin(); struct.parameters = new java.util.HashMap<java.lang.String,java.lang.String>(2*_map415.size); @org.apache.thrift.annotation.Nullable java.lang.String _key416; @org.apache.thrift.annotation.Nullable java.lang.String _val417; for (int _i418 = 0; _i418 < _map415.size; ++_i418) { _key416 = iprot.readString(); _val417 = iprot.readString(); struct.parameters.put(_key416, _val417); } iprot.readMapEnd(); } struct.setParametersIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // PRIVILEGES if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.privileges = new PrincipalPrivilegeSet(); struct.privileges.read(iprot); struct.setPrivilegesIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, PartitionWithoutSD struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.values != null) { oprot.writeFieldBegin(VALUES_FIELD_DESC); { oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.values.size())); for (java.lang.String _iter419 : struct.values) { oprot.writeString(_iter419); } oprot.writeListEnd(); } oprot.writeFieldEnd(); } oprot.writeFieldBegin(CREATE_TIME_FIELD_DESC); oprot.writeI32(struct.createTime); oprot.writeFieldEnd(); oprot.writeFieldBegin(LAST_ACCESS_TIME_FIELD_DESC); oprot.writeI32(struct.lastAccessTime); oprot.writeFieldEnd(); if (struct.relativePath != null) { oprot.writeFieldBegin(RELATIVE_PATH_FIELD_DESC); oprot.writeString(struct.relativePath); oprot.writeFieldEnd(); } if (struct.parameters != null) { oprot.writeFieldBegin(PARAMETERS_FIELD_DESC); { oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING, struct.parameters.size())); for (java.util.Map.Entry<java.lang.String, java.lang.String> _iter420 : struct.parameters.entrySet()) { oprot.writeString(_iter420.getKey()); oprot.writeString(_iter420.getValue()); } oprot.writeMapEnd(); } oprot.writeFieldEnd(); } if (struct.privileges != null) { if (struct.isSetPrivileges()) { oprot.writeFieldBegin(PRIVILEGES_FIELD_DESC); struct.privileges.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class PartitionWithoutSDTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { public PartitionWithoutSDTupleScheme getScheme() { return new PartitionWithoutSDTupleScheme(); } } private static class PartitionWithoutSDTupleScheme extends org.apache.thrift.scheme.TupleScheme<PartitionWithoutSD> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, PartitionWithoutSD struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet optionals = new java.util.BitSet(); if (struct.isSetValues()) { optionals.set(0); } if (struct.isSetCreateTime()) { optionals.set(1); } if (struct.isSetLastAccessTime()) { optionals.set(2); } if (struct.isSetRelativePath()) { optionals.set(3); } if (struct.isSetParameters()) { optionals.set(4); } if (struct.isSetPrivileges()) { optionals.set(5); } oprot.writeBitSet(optionals, 6); if (struct.isSetValues()) { { oprot.writeI32(struct.values.size()); for (java.lang.String _iter421 : struct.values) { oprot.writeString(_iter421); } } } if (struct.isSetCreateTime()) { oprot.writeI32(struct.createTime); } if (struct.isSetLastAccessTime()) { oprot.writeI32(struct.lastAccessTime); } if (struct.isSetRelativePath()) { oprot.writeString(struct.relativePath); } if (struct.isSetParameters()) { { oprot.writeI32(struct.parameters.size()); for (java.util.Map.Entry<java.lang.String, java.lang.String> _iter422 : struct.parameters.entrySet()) { oprot.writeString(_iter422.getKey()); oprot.writeString(_iter422.getValue()); } } } if (struct.isSetPrivileges()) { struct.privileges.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, PartitionWithoutSD struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; java.util.BitSet incoming = iprot.readBitSet(6); if (incoming.get(0)) { { org.apache.thrift.protocol.TList _list423 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRING); struct.values = new java.util.ArrayList<java.lang.String>(_list423.size); @org.apache.thrift.annotation.Nullable java.lang.String _elem424; for (int _i425 = 0; _i425 < _list423.size; ++_i425) { _elem424 = iprot.readString(); struct.values.add(_elem424); } } struct.setValuesIsSet(true); } if (incoming.get(1)) { struct.createTime = iprot.readI32(); struct.setCreateTimeIsSet(true); } if (incoming.get(2)) { struct.lastAccessTime = iprot.readI32(); struct.setLastAccessTimeIsSet(true); } if (incoming.get(3)) { struct.relativePath = iprot.readString(); struct.setRelativePathIsSet(true); } if (incoming.get(4)) { { org.apache.thrift.protocol.TMap _map426 = iprot.readMapBegin(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.STRING); struct.parameters = new java.util.HashMap<java.lang.String,java.lang.String>(2*_map426.size); @org.apache.thrift.annotation.Nullable java.lang.String _key427; @org.apache.thrift.annotation.Nullable java.lang.String _val428; for (int _i429 = 0; _i429 < _map426.size; ++_i429) { _key427 = iprot.readString(); _val428 = iprot.readString(); struct.parameters.put(_key427, _val428); } } struct.setParametersIsSet(true); } if (incoming.get(5)) { struct.privileges = new PrincipalPrivilegeSet(); struct.privileges.read(iprot); struct.setPrivilegesIsSet(true); } } } private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) { return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); } }
apache/tez
35,697
tez-dag/src/main/java/org/apache/tez/dag/history/logging/impl/HistoryEventJsonConversion.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.tez.dag.history.logging.impl; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.tez.common.ATSConstants; import org.apache.tez.dag.api.EdgeProperty; import org.apache.tez.dag.history.HistoryEvent; import org.apache.tez.dag.history.HistoryEventType; import org.apache.tez.dag.history.events.AMLaunchedEvent; import org.apache.tez.dag.history.events.AMStartedEvent; import org.apache.tez.dag.history.events.AppLaunchedEvent; import org.apache.tez.dag.history.events.ContainerLaunchedEvent; import org.apache.tez.dag.history.events.ContainerStoppedEvent; import org.apache.tez.dag.history.events.DAGFinishedEvent; import org.apache.tez.dag.history.events.DAGInitializedEvent; import org.apache.tez.dag.history.events.DAGRecoveredEvent; import org.apache.tez.dag.history.events.DAGStartedEvent; import org.apache.tez.dag.history.events.DAGSubmittedEvent; import org.apache.tez.dag.history.events.TaskAttemptFinishedEvent; import org.apache.tez.dag.history.events.TaskAttemptStartedEvent; import org.apache.tez.dag.history.events.TaskFinishedEvent; import org.apache.tez.dag.history.events.TaskStartedEvent; import org.apache.tez.dag.history.events.VertexConfigurationDoneEvent; import org.apache.tez.dag.history.events.VertexFinishedEvent; import org.apache.tez.dag.history.events.VertexInitializedEvent; import org.apache.tez.dag.history.events.VertexStartedEvent; import org.apache.tez.dag.history.logging.EntityTypes; import org.apache.tez.dag.history.utils.DAGUtils; import org.apache.tez.dag.records.TezVertexID; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; public final class HistoryEventJsonConversion { private HistoryEventJsonConversion() {} public static JSONObject convertToJson(HistoryEvent historyEvent) throws JSONException { if (!historyEvent.isHistoryEvent()) { throw new UnsupportedOperationException("Invalid Event, does not support history" + ", eventType=" + historyEvent.getEventType()); } JSONObject jsonObject; switch (historyEvent.getEventType()) { case APP_LAUNCHED: jsonObject = convertAppLaunchedEvent((AppLaunchedEvent) historyEvent); break; case AM_LAUNCHED: jsonObject = convertAMLaunchedEvent((AMLaunchedEvent) historyEvent); break; case AM_STARTED: jsonObject = convertAMStartedEvent((AMStartedEvent) historyEvent); break; case CONTAINER_LAUNCHED: jsonObject = convertContainerLaunchedEvent((ContainerLaunchedEvent) historyEvent); break; case CONTAINER_STOPPED: jsonObject = convertContainerStoppedEvent((ContainerStoppedEvent) historyEvent); break; case DAG_SUBMITTED: jsonObject = convertDAGSubmittedEvent((DAGSubmittedEvent) historyEvent); break; case DAG_INITIALIZED: jsonObject = convertDAGInitializedEvent((DAGInitializedEvent) historyEvent); break; case DAG_STARTED: jsonObject = convertDAGStartedEvent((DAGStartedEvent) historyEvent); break; case DAG_FINISHED: jsonObject = convertDAGFinishedEvent((DAGFinishedEvent) historyEvent); break; case VERTEX_INITIALIZED: jsonObject = convertVertexInitializedEvent((VertexInitializedEvent) historyEvent); break; case VERTEX_STARTED: jsonObject = convertVertexStartedEvent((VertexStartedEvent) historyEvent); break; case VERTEX_FINISHED: jsonObject = convertVertexFinishedEvent((VertexFinishedEvent) historyEvent); break; case TASK_STARTED: jsonObject = convertTaskStartedEvent((TaskStartedEvent) historyEvent); break; case TASK_FINISHED: jsonObject = convertTaskFinishedEvent((TaskFinishedEvent) historyEvent); break; case TASK_ATTEMPT_STARTED: jsonObject = convertTaskAttemptStartedEvent((TaskAttemptStartedEvent) historyEvent); break; case TASK_ATTEMPT_FINISHED: jsonObject = convertTaskAttemptFinishedEvent((TaskAttemptFinishedEvent) historyEvent); break; case VERTEX_CONFIGURE_DONE: jsonObject = convertVertexReconfigureDoneEvent((VertexConfigurationDoneEvent) historyEvent); break; case DAG_RECOVERED: jsonObject = convertDAGRecoveredEvent((DAGRecoveredEvent) historyEvent); break; case VERTEX_COMMIT_STARTED: case VERTEX_GROUP_COMMIT_STARTED: case VERTEX_GROUP_COMMIT_FINISHED: case DAG_COMMIT_STARTED: throw new UnsupportedOperationException("Invalid Event, does not support history" + ", eventType=" + historyEvent.getEventType()); default: throw new UnsupportedOperationException("Unhandled Event" + ", eventType=" + historyEvent.getEventType()); } return jsonObject; } private static JSONObject convertDAGRecoveredEvent(DAGRecoveredEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getDagID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); // Related Entities not needed as should have been done in // dag submission event JSONArray events = new JSONArray(); JSONObject recoverEvent = new JSONObject(); recoverEvent.put(ATSConstants.TIMESTAMP, event.getRecoveredTime()); recoverEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.DAG_RECOVERED.name()); JSONObject recoverEventInfo = new JSONObject(); recoverEventInfo.put(ATSConstants.APPLICATION_ATTEMPT_ID, event.getApplicationAttemptId().toString()); if (event.getRecoveredDagState() != null) { recoverEventInfo.put(ATSConstants.DAG_STATE, event.getRecoveredDagState().name()); } if (event.getRecoveryFailureReason() != null) { recoverEventInfo.put(ATSConstants.RECOVERY_FAILURE_REASON, event.getRecoveryFailureReason()); } recoverEvent.put(ATSConstants.EVENT_INFO, recoverEventInfo); events.put(recoverEvent); jsonObject.put(ATSConstants.EVENTS, events); return jsonObject; } private static JSONObject convertAppLaunchedEvent(AppLaunchedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + event.getApplicationId().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION.name()); // Other info to tag with Tez App JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.USER, event.getUser()); otherInfo.put(ATSConstants.CONFIG, new JSONObject( DAGUtils.convertConfigurationToATSMap(event.getConf()))); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertAMLaunchedEvent(AMLaunchedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + event.getApplicationAttemptId().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); // Related Entities JSONArray relatedEntities = new JSONArray(); JSONObject appEntity = new JSONObject(); appEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().getApplicationId().toString()); appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID); relatedEntities.put(appEntity); relatedEntities.put(appAttemptEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject initEvent = new JSONObject(); initEvent.put(ATSConstants.TIMESTAMP, event.getLaunchTime()); initEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.AM_LAUNCHED.name()); events.put(initEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info to tag with Tez AM JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.APP_SUBMIT_TIME, event.getAppSubmitTime()); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertAMStartedEvent(AMStartedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + event.getApplicationAttemptId().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); // Related Entities JSONArray relatedEntities = new JSONArray(); JSONObject appEntity = new JSONObject(); appEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().getApplicationId().toString()); appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID); relatedEntities.put(appEntity); relatedEntities.put(appAttemptEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime()); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.AM_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); return jsonObject; } private static JSONObject convertContainerLaunchedEvent(ContainerLaunchedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + event.getContainerId().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_CONTAINER_ID.name()); JSONArray relatedEntities = new JSONArray(); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); JSONObject containerEntity = new JSONObject(); containerEntity.put(ATSConstants.ENTITY, event.getContainerId().toString()); containerEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.CONTAINER_ID); relatedEntities.put(appAttemptEntity); relatedEntities.put(containerEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject launchEvent = new JSONObject(); launchEvent.put(ATSConstants.TIMESTAMP, event.getLaunchTime()); launchEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.CONTAINER_LAUNCHED.name()); events.put(launchEvent); jsonObject.put(ATSConstants.EVENTS, events); // TODO add other container info here? or assume AHS will have this? // TODO container logs? return jsonObject; } private static JSONObject convertContainerStoppedEvent(ContainerStoppedEvent event) throws JSONException { // structure is identical to ContainerLaunchedEvent JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + event.getContainerId().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_CONTAINER_ID.name()); JSONArray relatedEntities = new JSONArray(); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); JSONObject containerEntity = new JSONObject(); containerEntity.put(ATSConstants.ENTITY, event.getContainerId().toString()); containerEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.CONTAINER_ID); relatedEntities.put(appAttemptEntity); relatedEntities.put(containerEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject stopEvent = new JSONObject(); stopEvent.put(ATSConstants.TIMESTAMP, event.getStoppedTime()); stopEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.CONTAINER_STOPPED.name()); events.put(stopEvent); jsonObject.put(ATSConstants.EVENTS, events); // TODO add other container info here? or assume AHS will have this? // TODO container logs? // Other info JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.EXIT_STATUS, event.getExitStatus()); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertDAGFinishedEvent(DAGFinishedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getDAGID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); // Related Entities not needed as should have been done in // dag submission event // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject finishEvent = new JSONObject(); finishEvent.put(ATSConstants.TIMESTAMP, event.getFinishTime()); finishEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.DAG_FINISHED.name()); events.put(finishEvent); jsonObject.put(ATSConstants.EVENTS, events); JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.START_TIME, event.getStartTime()); otherInfo.put(ATSConstants.FINISH_TIME, event.getFinishTime()); otherInfo.put(ATSConstants.TIME_TAKEN, (event.getFinishTime() - event.getStartTime())); otherInfo.put(ATSConstants.STATUS, event.getState().name()); otherInfo.put(ATSConstants.DIAGNOSTICS, event.getDiagnostics()); otherInfo.put(ATSConstants.COUNTERS, DAGUtils.convertCountersToJSON(event.getTezCounters())); otherInfo.put(ATSConstants.COMPLETION_APPLICATION_ATTEMPT_ID, event.getApplicationAttemptId().toString()); final Map<String, Integer> dagTaskStats = event.getDagTaskStats(); if (dagTaskStats != null) { for(Entry<String, Integer> entry : dagTaskStats.entrySet()) { otherInfo.put(entry.getKey(), entry.getValue().intValue()); } } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertDAGInitializedEvent(DAGInitializedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getDAGID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); // Related Entities not needed as should have been done in // dag submission event JSONArray events = new JSONArray(); JSONObject initEvent = new JSONObject(); initEvent.put(ATSConstants.TIMESTAMP, event.getInitTime()); initEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.DAG_INITIALIZED.name()); events.put(initEvent); jsonObject.put(ATSConstants.EVENTS, events); JSONObject otherInfo = new JSONObject(); if (event.getVertexNameIDMap() != null) { Map<String, String> nameIdStrMap = new TreeMap<>(); for (Entry<String, TezVertexID> entry : event.getVertexNameIDMap().entrySet()) { nameIdStrMap.put(entry.getKey(), entry.getValue().toString()); } otherInfo.put(ATSConstants.VERTEX_NAME_ID_MAPPING, nameIdStrMap); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertDAGStartedEvent(DAGStartedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getDAGID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); // Related Entities not needed as should have been done in // dag submission event // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime()); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.DAG_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); return jsonObject; } private static JSONObject convertDAGSubmittedEvent(DAGSubmittedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getDAGID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); // Related Entities JSONArray relatedEntities = new JSONArray(); JSONObject tezAppEntity = new JSONObject(); tezAppEntity.put(ATSConstants.ENTITY, "tez_" + event.getApplicationAttemptId().getApplicationId().toString()); tezAppEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION.name()); JSONObject tezAppAttemptEntity = new JSONObject(); tezAppAttemptEntity.put(ATSConstants.ENTITY, "tez_" + event.getApplicationAttemptId().toString()); tezAppAttemptEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); JSONObject appEntity = new JSONObject(); appEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().getApplicationId().toString()); appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, event.getApplicationAttemptId().toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID); JSONObject userEntity = new JSONObject(); userEntity.put(ATSConstants.ENTITY, event.getUser()); userEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.USER); relatedEntities.put(tezAppEntity); relatedEntities.put(tezAppAttemptEntity); relatedEntities.put(appEntity); relatedEntities.put(appAttemptEntity); relatedEntities.put(userEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // filters JSONObject primaryFilters = new JSONObject(); primaryFilters.put(ATSConstants.DAG_NAME, event.getDAGName()); if (event.getDAGPlan().hasCallerContext() && event.getDAGPlan().getCallerContext().hasCallerId() && event.getDAGPlan().getCallerContext().hasCallerType()) { primaryFilters.put(ATSConstants.CALLER_CONTEXT_ID, event.getDAGPlan().getCallerContext().getCallerId()); primaryFilters.put(ATSConstants.CALLER_CONTEXT_TYPE, event.getDAGPlan().getCallerContext().getCallerType()); } if (event.getQueueName() != null) { primaryFilters.put(ATSConstants.DAG_QUEUE_NAME, event.getQueueName()); } jsonObject.put(ATSConstants.PRIMARY_FILTERS, primaryFilters); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject submitEvent = new JSONObject(); submitEvent.put(ATSConstants.TIMESTAMP, event.getSubmitTime()); submitEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.DAG_SUBMITTED.name()); events.put(submitEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info such as dag plan JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.DAG_PLAN, DAGUtils.generateSimpleJSONPlan(event.getDAGPlan())); if (event.getDAGPlan().hasCallerContext() && event.getDAGPlan().getCallerContext().hasCallerId() && event.getDAGPlan().getCallerContext().hasCallerType()) { otherInfo.put(ATSConstants.CALLER_CONTEXT_ID, event.getDAGPlan().getCallerContext().getCallerId()); otherInfo.put(ATSConstants.CALLER_CONTEXT_TYPE, event.getDAGPlan().getCallerContext().getCallerType()); } if (event.getQueueName() != null) { otherInfo.put(ATSConstants.DAG_QUEUE_NAME, event.getQueueName()); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertTaskAttemptFinishedEvent(TaskAttemptFinishedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getTaskAttemptID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ATTEMPT_ID.name()); // Events JSONArray events = new JSONArray(); JSONObject finishEvent = new JSONObject(); finishEvent.put(ATSConstants.TIMESTAMP, event.getFinishTime()); finishEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.TASK_ATTEMPT_FINISHED.name()); events.put(finishEvent); jsonObject.put(ATSConstants.EVENTS, events); JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.CREATION_TIME, event.getCreationTime()); otherInfo.put(ATSConstants.ALLOCATION_TIME, event.getAllocationTime()); otherInfo.put(ATSConstants.START_TIME, event.getStartTime()); otherInfo.put(ATSConstants.FINISH_TIME, event.getFinishTime()); otherInfo.put(ATSConstants.TIME_TAKEN, (event.getFinishTime() - event.getStartTime())); if (event.getCreationCausalTA() != null) { otherInfo.put(ATSConstants.CREATION_CAUSAL_ATTEMPT, event.getCreationCausalTA().toString()); } otherInfo.put(ATSConstants.STATUS, event.getState().name()); if (event.getTaskAttemptError() != null) { otherInfo.put(ATSConstants.TASK_ATTEMPT_ERROR_ENUM, event.getTaskAttemptError().name()); } if (event.getTaskFailureType() != null) { otherInfo.put(ATSConstants.TASK_FAILURE_TYPE, event.getTaskFailureType().name()); } otherInfo.put(ATSConstants.DIAGNOSTICS, event.getDiagnostics()); otherInfo.put(ATSConstants.COUNTERS, DAGUtils.convertCountersToJSON(event.getCounters())); if (event.getDataEvents() != null && !event.getDataEvents().isEmpty()) { otherInfo.put(ATSConstants.LAST_DATA_EVENTS, DAGUtils.convertDataEventDependencyInfoToJSON(event.getDataEvents())); } if (event.getNodeId() != null) { otherInfo.put(ATSConstants.NODE_ID, event.getNodeId().toString()); } if (event.getContainerId() != null) { otherInfo.put(ATSConstants.CONTAINER_ID, event.getContainerId().toString()); } if (event.getInProgressLogsUrl() != null) { otherInfo.put(ATSConstants.IN_PROGRESS_LOGS_URL, event.getInProgressLogsUrl()); } if (event.getCompletedLogsUrl() != null) { otherInfo.put(ATSConstants.COMPLETED_LOGS_URL, event.getCompletedLogsUrl()); } if (event.getNodeHttpAddress() != null) { otherInfo.put(ATSConstants.NODE_HTTP_ADDRESS, event.getNodeHttpAddress()); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertTaskAttemptStartedEvent(TaskAttemptStartedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getTaskAttemptID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ATTEMPT_ID.name()); // Related entities JSONArray relatedEntities = new JSONArray(); JSONObject nodeEntity = new JSONObject(); nodeEntity.put(ATSConstants.ENTITY, event.getNodeId().toString()); nodeEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.NODE_ID); JSONObject containerEntity = new JSONObject(); containerEntity.put(ATSConstants.ENTITY, event.getContainerId().toString()); containerEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.CONTAINER_ID); JSONObject taskEntity = new JSONObject(); taskEntity.put(ATSConstants.ENTITY, event.getTaskID().toString()); taskEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ID.name()); relatedEntities.put(nodeEntity); relatedEntities.put(containerEntity); relatedEntities.put(taskEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // Events JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime()); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.TASK_ATTEMPT_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.IN_PROGRESS_LOGS_URL, event.getInProgressLogsUrl()); otherInfo.put(ATSConstants.COMPLETED_LOGS_URL, event.getCompletedLogsUrl()); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertTaskFinishedEvent(TaskFinishedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getTaskID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ID.name()); // Events JSONArray events = new JSONArray(); JSONObject finishEvent = new JSONObject(); finishEvent.put(ATSConstants.TIMESTAMP, event.getFinishTime()); finishEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.TASK_FINISHED.name()); events.put(finishEvent); jsonObject.put(ATSConstants.EVENTS, events); JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.START_TIME, event.getStartTime()); otherInfo.put(ATSConstants.FINISH_TIME, event.getFinishTime()); otherInfo.put(ATSConstants.TIME_TAKEN, (event.getFinishTime() - event.getStartTime())); otherInfo.put(ATSConstants.STATUS, event.getState().name()); otherInfo.put(ATSConstants.DIAGNOSTICS, event.getDiagnostics()); otherInfo.put(ATSConstants.COUNTERS, DAGUtils.convertCountersToJSON(event.getTezCounters())); if (event.getSuccessfulAttemptID() != null) { otherInfo.put(ATSConstants.SUCCESSFUL_ATTEMPT_ID, event.getSuccessfulAttemptID().toString()); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertTaskStartedEvent(TaskStartedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getTaskID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_TASK_ID.name()); // Related entities JSONArray relatedEntities = new JSONArray(); JSONObject vertexEntity = new JSONObject(); vertexEntity.put(ATSConstants.ENTITY, event.getVertexID().toString()); vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name()); relatedEntities.put(vertexEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // Events JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime()); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.TASK_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info // TODO fix schedule/launch time to be events JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.START_TIME, event.getStartTime()); otherInfo.put(ATSConstants.SCHEDULED_TIME, event.getScheduledTime()); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertVertexFinishedEvent(VertexFinishedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name()); // Events JSONArray events = new JSONArray(); JSONObject finishEvent = new JSONObject(); finishEvent.put(ATSConstants.TIMESTAMP, event.getFinishTime()); finishEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.VERTEX_FINISHED.name()); events.put(finishEvent); jsonObject.put(ATSConstants.EVENTS, events); JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.FINISH_TIME, event.getFinishTime()); otherInfo.put(ATSConstants.TIME_TAKEN, (event.getFinishTime() - event.getStartTime())); otherInfo.put(ATSConstants.STATUS, event.getState().name()); otherInfo.put(ATSConstants.DIAGNOSTICS, event.getDiagnostics()); otherInfo.put(ATSConstants.COUNTERS, DAGUtils.convertCountersToJSON(event.getTezCounters())); otherInfo.put(ATSConstants.STATS, DAGUtils.convertVertexStatsToJSON(event.getVertexStats())); final Map<String, Integer> vertexTaskStats = event.getVertexTaskStats(); if (vertexTaskStats != null) { for(Entry<String, Integer> entry : vertexTaskStats.entrySet()) { otherInfo.put(entry.getKey(), entry.getValue().intValue()); } } if (event.getServicePluginInfo() != null) { otherInfo.put(ATSConstants.SERVICE_PLUGIN, DAGUtils.convertServicePluginToJSON(event.getServicePluginInfo())); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertVertexReconfigureDoneEvent(VertexConfigurationDoneEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name()); // Events JSONArray events = new JSONArray(); JSONObject updateEvent = new JSONObject(); updateEvent.put(ATSConstants.TIMESTAMP, event.getReconfigureDoneTime()); updateEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.VERTEX_CONFIGURE_DONE.name()); JSONObject eventInfo = new JSONObject(); eventInfo.put(ATSConstants.NUM_TASKS, event.getNumTasks()); if (event.getSourceEdgeProperties() != null && !event.getSourceEdgeProperties().isEmpty()) { JSONObject updatedEdgeManagers = new JSONObject(); for (Entry<String, EdgeProperty> entry : event.getSourceEdgeProperties().entrySet()) { updatedEdgeManagers.put(entry.getKey(), new JSONObject(DAGUtils.convertEdgeProperty(entry.getValue()))); } eventInfo.put(ATSConstants.UPDATED_EDGE_MANAGERS, updatedEdgeManagers); } updateEvent.put(ATSConstants.EVENT_INFO, eventInfo); events.put(updateEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info JSONObject otherInfo = new JSONObject(); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); // TODO add more on all other updated information return jsonObject; } private static JSONObject convertVertexInitializedEvent(VertexInitializedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name()); // Related entities JSONArray relatedEntities = new JSONArray(); JSONObject vertexEntity = new JSONObject(); vertexEntity.put(ATSConstants.ENTITY, event.getDAGID().toString()); vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); relatedEntities.put(vertexEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // Events JSONArray events = new JSONArray(); JSONObject initEvent = new JSONObject(); initEvent.put(ATSConstants.TIMESTAMP, event.getInitedTime()); initEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.VERTEX_INITIALIZED.name()); events.put(initEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info // TODO fix requested times to be events JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.VERTEX_NAME, event.getVertexName()); otherInfo.put(ATSConstants.INIT_REQUESTED_TIME, event.getInitRequestedTime()); otherInfo.put(ATSConstants.INIT_TIME, event.getInitedTime()); otherInfo.put(ATSConstants.NUM_TASKS, event.getNumTasks()); otherInfo.put(ATSConstants.PROCESSOR_CLASS_NAME, event.getProcessorName()); if (event.getServicePluginInfo() != null) { otherInfo.put(ATSConstants.SERVICE_PLUGIN, DAGUtils.convertServicePluginToJSON(event.getServicePluginInfo())); } jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } private static JSONObject convertVertexStartedEvent(VertexStartedEvent event) throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, event.getVertexID().toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_VERTEX_ID.name()); // Related entities JSONArray relatedEntities = new JSONArray(); JSONObject vertexEntity = new JSONObject(); vertexEntity.put(ATSConstants.ENTITY, event.getDAGID().toString()); vertexEntity.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_DAG_ID.name()); relatedEntities.put(vertexEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // Events JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, event.getStartTime()); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.VERTEX_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); // Other info // TODO fix requested times to be events JSONObject otherInfo = new JSONObject(); otherInfo.put(ATSConstants.START_REQUESTED_TIME, event.getStartRequestedTime()); otherInfo.put(ATSConstants.START_TIME, event.getStartTime()); jsonObject.put(ATSConstants.OTHER_INFO, otherInfo); return jsonObject; } }
apache/systemds
33,889
src/main/java/org/apache/sysds/runtime/compress/colgroup/mapping/AMapToData.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysds.runtime.compress.colgroup.mapping; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.sysds.runtime.compress.CompressedMatrixBlock; import org.apache.sysds.runtime.compress.DMLCompressionException; import org.apache.sysds.runtime.compress.colgroup.IMapToDataGroup; import org.apache.sysds.runtime.compress.colgroup.dictionary.Dictionary; import org.apache.sysds.runtime.compress.colgroup.dictionary.IDictionary; import org.apache.sysds.runtime.compress.colgroup.indexes.IColIndex; import org.apache.sysds.runtime.compress.colgroup.mapping.MapToFactory.MAP_TYPE; import org.apache.sysds.runtime.compress.colgroup.offset.AOffset; import org.apache.sysds.runtime.compress.colgroup.offset.AOffsetIterator; import org.apache.sysds.runtime.data.DenseBlock; import org.apache.sysds.runtime.data.SparseBlock; import org.apache.sysds.runtime.matrix.data.MatrixBlock; /** * This Class's job is to link into the dictionary entries for column groups. * * Column groups * * - DDC use this to map to map directly to the dictionary * * - SDC use this in collaboration with the offsets to only point to dictionary entries for non default values. */ public abstract class AMapToData implements Serializable { private static final long serialVersionUID = 1208906071822976041L; protected static final Log LOG = LogFactory.getLog(AMapToData.class.getName()); /** Number of unique values inside this map. */ private int nUnique; /** * Main constructor for AMapToData. * * NOTE! The value should be representable inside the map. This requirement is not checked. * * @param nUnique number of unique values. */ protected AMapToData(int nUnique) { this.nUnique = nUnique; } /** * Get the number of unique values inside this map. * * @return the unique count. */ public final int getUnique() { return nUnique; } /** * Set number of unique values. * * NOTE! The value should be representable inside the map. This requirement is not checked. * * @param nUnique the value to set. */ public final void setUnique(int nUnique) { this.nUnique = nUnique; } /** * Get the given index back as a integer * * @param n the index to get * @return the value represented in that cell as integer */ public abstract int getIndex(int n); /** * Shortcut method to support Integer objects, not really efficient but for the purpose of reusing code. * * @param n The index to set. * @param v The value to set. */ public void set(int n, Integer v) { set(n, (int) v); } /** * Set the index to the value. * * NOTE! The value should be representable inside the map. This requirement is not checked. * * @param n index to set. * @param v the value to set it to. */ public abstract void set(int n, int v); /** * set a range of values from another map. * * The given tm must only contain supported values, and it is not verified. * * @param l lower bound * @param u upper bound (not inclusive) * @param off offset to take values from tm * @param tm the other map to copy values from */ public abstract void set(int l, int u, int off, AMapToData tm); /** * Set the index to the value and get the contained value after. * * @param n index to set. * @param v the value to set it to. * @return v as encoded, note this value can be different that the one put in if the map is not able to represent the * value */ public abstract int setAndGet(int n, int v); /** * Fill the map with a given value. * * NOTE! The value should be representable inside the map. This requirement is not checked. * * @param v the value to fill */ public abstract void fill(int v); /** * Get the maximum value that is possible to allocate inside this map. * * @return The maximum value. */ public abstract int getUpperBoundValue(); /** * Get the in memory size of this Mapping object. * * @return The size in Bytes. */ public abstract long getInMemorySize(); /** * Get the size of this Mapping object on disk. * * @return The on disk size in Bytes. */ public abstract long getExactSizeOnDisk(); /** * The size of the Mapping object, signaling how many value cells are stored in this mapping object. * * @return The length of the mapping object. */ public abstract int size(); /** * Serialize this object to the DataOutput given. * * @param out The object to serialize this object into. * @throws IOException An IO exception if the Serialization fails. */ public abstract void write(DataOutput out) throws IOException; /** * Replace v with r for all entries, * * NOTE! It is assumed that you call this correctly: * * - with two distinct values that is representable inside the given AMapToData. * * @param v The value to replace * @param r The value to put instead */ public abstract void replace(int v, int r); public abstract MAP_TYPE getType(); /** * Pre aggregate a dense matrix m into pre, subject to only including a row segment and column segment. * * @param m The dense matrix values to preaggregate * @param preAV The preAggregate double array populate with the summed values of m * @param rl The row start in m * @param ru The row end in m * @param cl The column start in m * @param cu The column end in m */ public final void preAggregateDense(MatrixBlock m, double[] preAV, int rl, int ru, int cl, int cu) { final DenseBlock db = m.getDenseBlock(); if(rl == ru - 1) preAggregateDenseSingleRow(db.values(rl), db.pos(rl), preAV, cl, cu); else preAggregateDenseMultiRow(m, preAV, rl, ru, cl, cu); } /** * PreAggregate Dense on a single row. * * @param mV The DenseMatrix Values from the input matrix block for the specific row given * @param off The offset into the mV that the row values start from * @param preAV The PreAggregate value target to preAggregate into * @param cl The column index to start at * @param cu The column index to stop at (not inclusive) */ protected void preAggregateDenseSingleRow(double[] mV, int off, double[] preAV, int cl, int cu) { if(cu - cl > 64) preAggregateDenseToRowBy8(mV, preAV, cl, cu, off); else { off += cl; for(int rc = cl; rc < cu; rc++, off++) preAV[getIndex(rc)] += mV[off]; } } protected void preAggregateDenseToRowBy8(double[] mV, double[] preAV, int cl, int cu, int off) { final int h = (cu - cl) % 8; off += cl; for(int rc = cl; rc < cl + h; rc++, off++) preAV[getIndex(rc)] += mV[off]; for(int rc = cl + h; rc < cu; rc += 8, off += 8) preAggregateDenseToRowVec8(mV, preAV, rc, off); } protected void preAggregateDenseToRowVec8(double[] mV, double[] preAV, int rc, int off) { preAV[getIndex(rc)] += mV[off]; preAV[getIndex(rc + 1)] += mV[off + 1]; preAV[getIndex(rc + 2)] += mV[off + 2]; preAV[getIndex(rc + 3)] += mV[off + 3]; preAV[getIndex(rc + 4)] += mV[off + 4]; preAV[getIndex(rc + 5)] += mV[off + 5]; preAV[getIndex(rc + 6)] += mV[off + 6]; preAV[getIndex(rc + 7)] += mV[off + 7]; } /** * PreAggregate from Dense Matrix, and handle multiple rows, * * @param m The Matrix to preAggregate. * @param preAV The target dense array to preAggregate into * @param rl The row to start at * @param ru The row to end at (not inclusive) * @param cl The column to start at * @param cu The column to end at (not inclusive) */ protected void preAggregateDenseMultiRow(MatrixBlock m, double[] preAV, int rl, int ru, int cl, int cu) { final int nVal = getUnique(); final DenseBlock db = m.getDenseBlock(); if(db.isContiguous()) { final double[] mV = m.getDenseBlockValues(); final int nCol = m.getNumColumns(); preAggregateDenseMultiRowContiguous(mV, nCol, nVal, preAV, rl, ru, cl, cu); } else throw new NotImplementedException(); } protected void preAggregateDenseMultiRowContiguous(double[] mV, int nCol, int nVal, double[] preAV, int rl, int ru, int cl, int cu) { if(cu - cl > 64) preAggregateDenseMultiRowContiguousBy8(mV, nCol, nVal, preAV, rl, ru, cl, cu); else preAggregateDenseMultiRowContiguousBy1(mV, nCol, nVal, preAV, rl, ru, cl, cu); } protected void preAggregateDenseMultiRowContiguousBy8(double[] mV, int nCol, int nVal, double[] preAV, int rl, int ru, int cl, int cu) { final int h = (cu - cl) % 8; preAggregateDenseMultiRowContiguousBy1(mV, nCol, nVal, preAV, rl, ru, cl, cl + h); final int offR = nCol * rl; final int offE = nCol * ru; for(int c = cl + h; c < cu; c += 8) { final int id1 = getIndex(c), id2 = getIndex(c + 1), id3 = getIndex(c + 2), id4 = getIndex(c + 3), id5 = getIndex(c + 4), id6 = getIndex(c + 5), id7 = getIndex(c + 6), id8 = getIndex(c + 7); final int start = c + offR; final int end = c + offE; int nValOff = 0; for(int off = start; off < end; off += nCol) { preAV[id1 + nValOff] += mV[off]; preAV[id2 + nValOff] += mV[off + 1]; preAV[id3 + nValOff] += mV[off + 2]; preAV[id4 + nValOff] += mV[off + 3]; preAV[id5 + nValOff] += mV[off + 4]; preAV[id6 + nValOff] += mV[off + 5]; preAV[id7 + nValOff] += mV[off + 6]; preAV[id8 + nValOff] += mV[off + 7]; nValOff += nVal; } } } protected void preAggregateDenseMultiRowContiguousBy1(double[] mV, int nCol, int nVal, double[] preAV, int rl, int ru, int cl, int cu) { final int offR = nCol * rl; final int offE = nCol * ru; for(int c = cl; c < cu; c++) { final int idx = getIndex(c); final int start = c + offR; final int end = c + offE; for(int offOut = idx, off = start; off < end; offOut += nVal, off += nCol) { preAV[offOut] += mV[off]; } } } /** * PreAggregate a Dense Matrix at index offsets. * * @param m The DenseBlock to preAggregate * @param preAV The target double array to put the preAggregate into * @param rl The row to start at * @param ru The row to end at (not inclusive) * @param cl The column in m to start from * @param cu The column in m to end at (not inclusive) * @param indexes The Offset Indexes to iterate through */ public final void preAggregateDense(DenseBlock m, double[] preAV, int rl, int ru, int cl, int cu, AOffset indexes) { indexes.preAggregateDenseMap(m, preAV, rl, ru, cl, cu, getUnique(), this); } /** * PreAggregate the SparseBlock in the range of rows given. * * @param sb The SparseBlock to preAggregate * @param preAV The target double array to put the preAggregate into * @param rl The row to start at * @param ru The row to end at (not inclusive) * @param indexes The Offset Indexes to iterate through */ public final void preAggregateSparse(SparseBlock sb, double[] preAV, int rl, int ru, AOffset indexes) { indexes.preAggSparseMap(sb, preAV, rl, ru, getUnique(), this); } /** * PreAggregate the sparseblock in the range of rows given. * * @param sb Sparse block to preAggregate from * @param preAV Pre aggregate target * @param rl row index in sb * @param ru upper row index in sp (not inclusive) */ public final void preAggregateSparse(SparseBlock sb, double[] preAV, int rl, int ru) { if(rl == ru - 1) preAggregateSparseSingleRow(sb, preAV, rl); else preAggregateSparseMultiRow(sb, preAV, rl, ru); } private final void preAggregateSparseSingleRow(final SparseBlock sb, final double[] preAV, final int r) { if(sb.isEmpty(r)) return; final int apos = sb.pos(r); final int alen = sb.size(r) + apos; final int[] aix = sb.indexes(r); final double[] avals = sb.values(r); for(int j = apos; j < alen; j++) preAV[getIndex(aix[j])] += avals[j]; } private final void preAggregateSparseMultiRow(final SparseBlock sb, final double[] preAV, final int rl, final int ru) { final int unique = getUnique(); for(int r = rl; r < ru; r++) { if(sb.isEmpty(r)) continue; final int apos = sb.pos(r); final int alen = sb.size(r) + apos; final int[] aix = sb.indexes(r); final double[] avals = sb.values(r); final int off = unique * (r - rl); for(int j = apos; j < alen; j++) preAV[off + getIndex(aix[j])] += avals[j]; } } /** * Get the number of counts of each unique value contained in this map. Note that in the case the mapping is shorter * than number of rows the counts sum to the number of mapped values not the number of rows. * * @return The counts */ public final int[] getCounts() { return getCounts(new int[getUnique()]); } /** * Get the number of counts of each unique value contained in this map. Note that in the case the mapping is shorter * than number of rows the counts sum to the number of mapped values not the number of rows. * * @param counts The object to return. * @return The counts */ public abstract int[] getCounts(int[] counts); /** * PreAggregate into dictionary with two sides of DDC. * * @param tm Map of other side * @param td Dictionary to take values from (other side dictionary) * @param ret The output dictionary to aggregate into * @param nCol The number of columns */ public final void preAggregateDDC_DDC(AMapToData tm, IDictionary td, Dictionary ret, int nCol) { if(nCol == 1) preAggregateDDC_DDCSingleCol(tm, td.getValues(), ret.getValues()); else preAggregateDDC_DDCMultiCol(tm, td, ret.getValues(), nCol); } /** * PreAggregate into dictionary with two sides of DDC guaranteed to only have one column tuples. * * @param tm Map of other side * @param td Dictionary to take values from (other side dictionary) * @param ret The output dictionary to aggregate into */ protected void preAggregateDDC_DDCSingleCol(AMapToData tm, double[] td, double[] v) { final int sz = size(); final int h = sz % 8; for(int r = 0; r < h; r++) v[getIndex(r)] += td[tm.getIndex(r)]; for(int r = h; r < sz; r += 8) preAggregateDDC_DDCSingleCol_vec(tm, td, v, r); } protected void preAggregateDDC_DDCSingleCol_vec(AMapToData tm, double[] td, double[] v, int r) { final int r2 = r + 1, r3 = r + 2, r4 = r + 3, r5 = r + 4, r6 = r + 5, r7 = r + 6, r8 = r + 7; v[getIndex(r)] += td[tm.getIndex(r)]; v[getIndex(r2)] += td[tm.getIndex(r2)]; v[getIndex(r3)] += td[tm.getIndex(r3)]; v[getIndex(r4)] += td[tm.getIndex(r4)]; v[getIndex(r5)] += td[tm.getIndex(r5)]; v[getIndex(r6)] += td[tm.getIndex(r6)]; v[getIndex(r7)] += td[tm.getIndex(r7)]; v[getIndex(r8)] += td[tm.getIndex(r8)]; } /** * PreAggregate into dictionary with two sides of DDC guaranteed to multiple column tuples. * * @param tm Map of other side that indicate the indexes to take out and put into ret * @param td Dictionary to take values from (other side dictionary) * @param ret The output dictionary to aggregate into * @param nCol The number of columns in td */ protected void preAggregateDDC_DDCMultiCol(final AMapToData tm, final IDictionary td, final double[] v, final int nCol) { final int sz = size(); final int h = sz % 8; for(int r = 0; r < h; r++) td.addToEntry(v, tm.getIndex(r), getIndex(r), nCol); for(int r = h; r < sz; r += 8) preAggregateDDC_DDCMultiCol_vec(tm, td, v, nCol, r); } protected void preAggregateDDC_DDCMultiCol_vec(final AMapToData tm, final IDictionary td, final double[] v, final int nCol, final int r) { final int r2 = r + 1, r3 = r + 2, r4 = r + 3, r5 = r + 4, r6 = r + 5, r7 = r + 6, r8 = r + 7; td.addToEntryVectorized(v, // tm.getIndex(r), tm.getIndex(r2), tm.getIndex(r3), tm.getIndex(r4), tm.getIndex(r5), tm.getIndex(r6), tm.getIndex(r7), tm.getIndex(r8), getIndex(r), // getIndex(r2), getIndex(r3), getIndex(r4), getIndex(r5), getIndex(r6), getIndex(r7), getIndex(r8), nCol); } /** * PreAggregate into SDCZero dictionary from DDC dictionary. * * @param tm Map of other side * @param td Dictionary to take values from (other side dictionary) * @param tof The offset index structure of the SDC side * @param ret The output dictionary to aggregate into * @param nCol The number of columns in output and td dictionary */ public final void preAggregateDDC_SDCZ(AMapToData tm, IDictionary td, AOffset tof, Dictionary ret, int nCol) { if(nCol == 1) preAggregateDDC_SDCZSingleCol(tm, td.getValues(), tof, ret.getValues()); else preAggregateDDC_SDCZMultiCol(tm, td, tof, ret.getValues(), nCol); } public void preAggregateDDC_SDCZSingleCol(AMapToData tm, double[] td, AOffset tof, double[] v) { final AOffsetIterator itThat = tof.getOffsetIterator(); final int size = tm.size() - 1; for(int i = 0; i < size; i++) { final int to = getIndex(itThat.value()); final int fr = tm.getIndex(i); v[to] += td[fr]; itThat.next(); } final int to = getIndex(itThat.value()); final int fr = tm.getIndex(size); v[to] += td[fr]; } public void preAggregateDDC_SDCZMultiCol(AMapToData tm, IDictionary td, AOffset tof, double[] v, int nCol) { final AOffsetIterator it = tof.getOffsetIterator(); final int size = tm.size() - 1; int i = (size > 8) ? preAggregateDDC_SDCZMultiCol_vect(tm, td, v, nCol, it, size) : 0; for(; i < size; i++) { final int to = getIndex(it.value()); final int fr = tm.getIndex(i); td.addToEntry(v, fr, to, nCol); it.next(); } final int to = getIndex(it.value()); final int fr = tm.getIndex(size); td.addToEntry(v, fr, to, nCol); } private int preAggregateDDC_SDCZMultiCol_vect(AMapToData tm, IDictionary td, double[] v, int nCol, AOffsetIterator it, int size) { final int h = size % 8; int i = 0; while(i < size - h) { int t1 = it.value(), t2 = it.next(), t3 = it.next(), t4 = it.next(), t5 = it.next(), t6 = it.next(), t7 = it.next(), t8 = it.next(); t1 = getIndex(t1); t2 = getIndex(t2); t3 = getIndex(t3); t4 = getIndex(t4); t5 = getIndex(t5); t6 = getIndex(t6); t7 = getIndex(t7); t8 = getIndex(t8); int f1 = tm.getIndex(i), f2 = tm.getIndex(i + 1), f3 = tm.getIndex(i + 2), f4 = tm.getIndex(i + 3), f5 = tm.getIndex(i + 4), f6 = tm.getIndex(i + 5), f7 = tm.getIndex(i + 6), f8 = tm.getIndex(i + 7); i += 8; it.next(); td.addToEntryVectorized(v, f1, f2, f3, f4, f5, f6, f7, f8, t1, t2, t3, t4, t5, t6, t7, t8, nCol); } return i; } /** * PreAggregate into DDC dictionary from SDCZero dictionary. * * @param tm Map of other side * @param td Dictionary to take values from (other side dictionary) * @param of Offsets of the SDC to look into DDC * @param ret The output dictionary to aggregate into * @param nCol The number of columns in output and td dictionary */ public final void preAggregateSDCZ_DDC(AMapToData tm, IDictionary td, AOffset of, Dictionary ret, int nCol) { if(nCol == 1) preAggregateSDCZ_DDCSingleCol(tm, td.getValues(), of, ret.getValues()); else preAggregateSDCZ_DDCMultiCol(tm, td, of, ret.getValues(), nCol); } protected void preAggregateSDCZ_DDCSingleCol(AMapToData tm, double[] td, AOffset of, double[] v) { final AOffsetIterator itThis = of.getOffsetIterator(); final int size = size() - 1; int tv = itThis.value(); for(int i = 0; i < size; i++) { v[getIndex(i)] += td[tm.getIndex(tv)]; tv = itThis.next(); } v[getIndex(size)] += td[tm.getIndex(tv)]; } protected void preAggregateSDCZ_DDCMultiCol(AMapToData tm, IDictionary td, AOffset of, double[] v, int nCol) { final AOffsetIterator itThis = of.getOffsetIterator(); final int size = size() - 1; int i = (size > 8) ? preAggregateSDCZ_DDCMultiCol_vect(tm, td, v, nCol, itThis, size) : 0; int tv = itThis.value(); for(; i < size; i++) { td.addToEntry(v, tm.getIndex(tv), getIndex(i), nCol); tv = itThis.next(); } td.addToEntry(v, tm.getIndex(tv), getIndex(size), nCol); } private int preAggregateSDCZ_DDCMultiCol_vect(AMapToData tm, IDictionary td, double[] v, int nCol, AOffsetIterator it, int size) { final int h = size % 8; int i = 0; while(i < size - h) { int t1 = getIndex(i), t2 = getIndex(i + 1), t3 = getIndex(i + 2), t4 = getIndex(i + 3), t5 = getIndex(i + 4), t6 = getIndex(i + 5), t7 = getIndex(i + 6), t8 = getIndex(i + 7); int f1 = it.value(), f2 = it.next(), f3 = it.next(), f4 = it.next(), f5 = it.next(), f6 = it.next(), f7 = it.next(), f8 = it.next(); f1 = tm.getIndex(f1); f2 = tm.getIndex(f2); f3 = tm.getIndex(f3); f4 = tm.getIndex(f4); f5 = tm.getIndex(f5); f6 = tm.getIndex(f6); f7 = tm.getIndex(f7); f8 = tm.getIndex(f8); i += 8; it.next(); td.addToEntryVectorized(v, f1, f2, f3, f4, f5, f6, f7, f8, t1, t2, t3, t4, t5, t6, t7, t8, nCol); } return i; } public final void preAggregateSDCZ_SDCZ(AMapToData tm, IDictionary td, AOffset tof, AOffset of, Dictionary ret, int nCol) { if(nCol == 1) preAggregateSDCZ_SDCZSingleCol(tm, td.getValues(), tof, of, ret.getValues()); else preAggregateSDCZ_SDCZMultiCol(tm, td, tof, of, ret.getValues(), nCol); } private final void preAggregateSDCZ_SDCZSingleCol(AMapToData tm, double[] td, AOffset tof, AOffset of, double[] dv) { final AOffsetIterator itThat = tof.getOffsetIterator(); final AOffsetIterator itThis = of.getOffsetIterator(); final int tSize = tm.size() - 1, size = size() - 1; preAggregateSDCZ_SDCZSingleCol(tm, td, dv, itThat, itThis, tSize, size); } protected void preAggregateSDCZ_SDCZSingleCol(AMapToData tm, double[] td, double[] dv, AOffsetIterator itThat, AOffsetIterator itThis, int tSize, int size) { int i = 0, j = 0, tv = itThat.value(), v = itThis.value(); // main preAggregate process while(i < tSize && j < size) { if(tv == v) { dv[getIndex(j)] += td[tm.getIndex(i)]; tv = itThat.next(); v = itThis.next(); i++; j++; } else if(tv < v) { tv = itThat.next(); i++; } else { v = itThis.next(); j++; } } // Remaining part (very small so not really main performance bottleneck) preAggregateSDCZ_SDCZMultiCol_tail(tm, this, Dictionary.create(td), dv, 1, itThat, itThis, tSize, size, i, j); } protected void preAggregateSDCZ_SDCZMultiCol(AMapToData tm, IDictionary td, AOffset tof, AOffset of, double[] dv, int nCol) { final AOffsetIterator itThat = tof.getOffsetIterator(); final AOffsetIterator itThis = of.getOffsetIterator(); final int tSize = tm.size() - 1, size = size() - 1; int i = 0, j = 0; // main preAggregate process while(i < tSize && j < size) { final int tv = itThat.value(); final int v = itThis.value(); if(tv == v) { final int fr = tm.getIndex(i); final int to = getIndex(j); td.addToEntry(dv, fr, to, nCol); itThat.next(); itThis.next(); i++; j++; } else if(tv < v) { itThat.next(); i++; } else { itThis.next(); j++; } } // Remaining part (very small so not really main performance bottleneck) preAggregateSDCZ_SDCZMultiCol_tail(tm, this, td, dv, nCol, itThat, itThis, tSize, size, i, j); } protected static void preAggregateSDCZ_SDCZMultiCol_tail(AMapToData tm, AMapToData m, IDictionary td, double[] dv, int nCol, AOffsetIterator itThat, AOffsetIterator itThis, int tSize, int size, int i, int j) { int tv = itThat.value(); int v = itThis.value(); if(tv == v) { final int fr = tm.getIndex(i); final int to = m.getIndex(j); td.addToEntry(dv, fr, to, nCol); return; } while(i < tSize && tv < v) { // this is at final itThat.next(); i++; tv = itThat.value(); if(tv == v) { final int fr = tm.getIndex(i); final int to = m.getIndex(j); td.addToEntry(dv, fr, to, nCol); return; } } while(j < size && v < tv) { // that is at final itThis.next(); j++; v = itThis.value(); if(tv == v) { final int fr = tm.getIndex(i); final int to = m.getIndex(j); td.addToEntry(dv, fr, to, nCol); return; } } } public void preAggregateRLE_DDC(int[] ptr, char[] data, IDictionary td, Dictionary ret, int nCol) { if(nCol == 1) preAggregateRLE_DDCSingleCol(ptr, data, td.getValues(), ret.getValues()); else preAggregateRLE_DDCMultiCol(ptr, data, td, ret.getValues(), nCol); } protected void preAggregateRLE_DDCSingleCol(int[] ptr, char[] data, double[] td, double[] ret) { // find each index in RLE, and aggregate into those. for(int k = 0; k < ret.length; k++) { // for each run in RLE final int blen = ptr[k + 1]; for(int apos = ptr[k], rs = 0, re = 0; apos < blen; apos += 2) { rs = re + data[apos]; re = rs + data[apos + 1]; for(int rix = rs; rix < re; rix++) ret[k] += td[getIndex(rix)]; } } } protected void preAggregateRLE_DDCMultiCol(int[] ptr, char[] data, IDictionary td, double[] ret, int nCol) { // find each index in RLE, and aggregate into those. for(int k = 0; k < ret.length / nCol; k++) { // for each run in RLE final int blen = ptr[k + 1]; for(int apos = ptr[k], rs = 0, re = 0; apos < blen; apos += 2) { rs = re + data[apos]; re = rs + data[apos + 1]; for(int rix = rs; rix < re; rix++) td.addToEntry(ret, getIndex(rix), k, nCol); } } } public void preAggregateDDC_RLE(int[] ptr, char[] data, IDictionary td, Dictionary ret, int nCol) { // find each index in RLE, and aggregate into those. double[] v = ret.getValues(); for(int k = 0; k < ptr.length - 1; k++) { // for each run in RLE final int blen = ptr[k + 1]; for(int apos = ptr[k], rs = 0, re = 0; apos < blen; apos += 2) { rs = re + data[apos]; re = rs + data[apos + 1]; for(int rix = rs; rix < re; rix++) td.addToEntry(v, k, getIndex(rix), nCol); } } } /** * Copy the values in this map into another mapping object. * * NOTE! All contained vales should be representable inside the map given. This requirement is not checked. * * @param d Map to copy all values into. */ public void copy(AMapToData d) { if(d.nUnique == 1) fill(0); else if(d instanceof MapToBit) copyBit((MapToBit) d); else if(d instanceof MapToInt) copyInt((MapToInt) d); else { final int sz = size(); for(int i = 0; i < sz; i++) set(i, d.getIndex(i)); } } protected void copyInt(MapToInt d) { copyInt(d.getData()); } /** * Copy the values of the given array into this. * * Note that this operation stops at the length of this AMapToData * * Therefore the given d length can not be longer than this size. * * @param d The array to copy */ public void copyInt(int[] d) { copyInt(d, 0, Math.min(d.length, size())); } public abstract void copyInt(int[] d, int start, int end); public void copyBit(MapToBit d) { fill(0); for(int i = d.nextSetBit(0); i >= 0; i = d.nextSetBit(i + 1)) { set(i, 1); } } public int getMax() { int m = -1; for(int i = 0; i < size(); i++) { int v = getIndex(i); m = v > m ? v : m; } return m; } /** * Reallocate the map, to a smaller instance if applicable. Note it does not change the length of the array, just the * datatype. * * Note that it returns the input if the input is the smallest representation that fits, otherwise it will return * something that is smaller. * * @param unique The number of tuples that should be supported in the resulting map * @return The returned hopefully reduced map. */ public abstract AMapToData resize(int unique); /** * Count the number of runs inside the map. * * @return The number of runs */ public abstract int countRuns(); /** * Count the number of runs inside the map, but sparse with offsets. * * @param off The sparse offsets to consider counting the runs from. * @return count of runs. */ public int countRuns(AOffset off) { int c = 1; final int size = size(); final AOffsetIterator of = off.getOffsetIterator(); for(int i = 1; i < size; i++) { int id = of.value(); if(id + 1 == of.next()) c += getIndex(i - 1) == getIndex(i) ? 0 : 1; else c++; } return c; } /** * Slice out the range from lower to upper from this map toData. * * @param l Low value to slice from * @param u high value to slice to (not inclusive) * @return A new map containing only the values from the range. */ public abstract AMapToData slice(int l, int u); public abstract AMapToData append(AMapToData t); public abstract AMapToData appendN(IMapToDataGroup[] d); @Override public boolean equals(Object e) { return this == e || // same object or (e instanceof AMapToData && this.equals((AMapToData) e)); } /** * Indicate if the given encoding is equivalent to this encoding * * @param e The other encoding to be compared with this * @return If the encoding is equivalent */ public abstract boolean equals(AMapToData e); /** Debugging verification that this mapping is correctly made. */ public void verify() { if(CompressedMatrixBlock.debug) { for(int i = 0; i < size(); i++) { if(getIndex(i) >= nUnique) { throw new DMLCompressionException("Invalid construction of Mapping data containing values above unique"); } } } } public void lmSparseMatrixRow(SparseBlock sb, final int r, DenseBlock db, final IColIndex colIndexes, final IDictionary dict) { if(sb.isEmpty(r)) return; // dense output blocks locations final int pos = db.pos(r); final double[] retV = db.values(r); // sparse left block locations final int apos = sb.pos(r); final int alen = sb.size(r) + apos; final int[] aix = sb.indexes(r); final double[] aval = sb.values(r); for(int i = apos; i < alen; i++) dict.multiplyScalar(aval[i], retV, pos, getIndex(aix[i]), colIndexes); } public void decompressToRange(double[] c, int rl, int ru, int offR, double[] values) { if(offR == 0) decompressToRangeNoOff(c, rl, ru, values); else decompressToRangeOff(c, rl, ru, offR, values); } protected void decompressToRangeOff(double[] c, int rl, int ru, int offR, double[] values) { for(int i = rl, offT = rl + offR; i < ru; i++, offT++) c[offT] += values[getIndex(i)]; } protected void decompressToRangeNoOffBy8(double[] c, int r, double[] values) { c[r] += values[getIndex(r)]; c[r + 1] += values[getIndex(r + 1)]; c[r + 2] += values[getIndex(r + 2)]; c[r + 3] += values[getIndex(r + 3)]; c[r + 4] += values[getIndex(r + 4)]; c[r + 5] += values[getIndex(r + 5)]; c[r + 6] += values[getIndex(r + 6)]; c[r + 7] += values[getIndex(r + 7)]; } protected void decompressToRangeNoOff(double[] c, int rl, int ru, double[] values) { final int h = (ru - rl) % 8; for(int rc = rl; rc < rl + h; rc++) c[rc] += values[getIndex(rc)]; for(int rc = rl + h; rc < ru; rc += 8) decompressToRangeNoOffBy8(c, rc, values); } /** * Split this mapping into x smaller mappings according to round robin. * * @param multiplier The number of smaller mappings to construct * @return The list of smaller mappings */ public AMapToData[] splitReshapeDDC(final int multiplier) { final int s = size(); final AMapToData[] ret = new AMapToData[multiplier]; final int eachSize = s / multiplier; for(int i = 0; i < multiplier; i++) ret[i] = MapToFactory.create(eachSize, getUnique()); final int blkz = Math.max(eachSize / 8, 2048) * multiplier; for(int i = 0; i < s; i += blkz) splitReshapeDDCBlock(ret, multiplier, i, Math.min(i + blkz, s)); return ret; } public AMapToData[] splitReshapeDDCPushDown(final int multiplier, final ExecutorService pool) throws Exception { final int s = size(); final AMapToData[] ret = new AMapToData[multiplier]; final int eachSize = s / multiplier; for(int i = 0; i < multiplier; i++) ret[i] = MapToFactory.create(eachSize, getUnique()); final int blkz = Math.max(eachSize / 8, 2048) * multiplier; List<Future<?>> tasks = new ArrayList<>(); for(int i = 0; i < s; i += blkz) { final int start = i; final int end = Math.min(i + blkz, s); tasks.add(pool.submit(() -> splitReshapeDDCBlock(ret, multiplier, start, end))); } for(Future<?> t : tasks) t.get(); return ret; } private void splitReshapeDDCBlock(final AMapToData[] ret, final int multiplier, final int start, final int end) { for(int i = start; i < end; i += multiplier) splitReshapeDDCRow(ret, multiplier, i); } private void splitReshapeDDCRow(final AMapToData[] ret, final int multiplier, final int i) { final int off = i / multiplier; final int end = i + multiplier; for(int j = i; j < end; j++) ret[j % multiplier].set(off, getIndex(j)); } @Override public String toString() { final int sz = size(); StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName()); sb.append("["); for(int i = 0; i < sz - 1; i++) sb.append(getIndex(i) + ", "); sb.append(getIndex(sz - 1)); sb.append("]"); return sb.toString(); } }
apache/flink-cdc
35,247
flink-cdc-connect/flink-cdc-source-connectors/flink-connector-mongodb-cdc/src/test/java/org/apache/flink/cdc/connectors/mongodb/source/MongoDBParallelSourceITCase.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.cdc.connectors.mongodb.source; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.cdc.connectors.base.options.StartupOptions; import org.apache.flink.cdc.connectors.base.source.utils.hooks.SnapshotPhaseHook; import org.apache.flink.cdc.connectors.base.source.utils.hooks.SnapshotPhaseHooks; import org.apache.flink.cdc.connectors.mongodb.source.config.MongoDBSourceConfig; import org.apache.flink.cdc.connectors.mongodb.source.utils.MongoUtils; import org.apache.flink.cdc.connectors.mongodb.utils.MongoDBTestUtils.FailoverPhase; import org.apache.flink.cdc.connectors.mongodb.utils.MongoDBTestUtils.FailoverType; import org.apache.flink.cdc.connectors.mongodb.utils.TestTable; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.flink.table.catalog.ResolvedSchema; import org.apache.flink.table.catalog.UniqueConstraint; import org.apache.flink.table.data.RowData; import org.apache.flink.types.Row; import org.apache.flink.util.CloseableIterator; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import org.bson.Document; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBAssertUtils.assertEqualsInAnyOrder; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBContainer.FLINK_USER; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBContainer.FLINK_USER_PASSWORD; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBTestUtils.fetchRowData; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBTestUtils.fetchRows; import static org.apache.flink.cdc.connectors.mongodb.utils.MongoDBTestUtils.triggerFailover; import static org.apache.flink.table.api.DataTypes.BIGINT; import static org.apache.flink.table.api.DataTypes.STRING; import static org.apache.flink.table.catalog.Column.physical; import static org.apache.flink.util.Preconditions.checkState; /** IT tests for {@link MongoDBSource}. */ @Timeout(value = 300, unit = TimeUnit.SECONDS) class MongoDBParallelSourceITCase extends MongoDBSourceTestBase { private static final int USE_POST_LOWWATERMARK_HOOK = 1; private static final int USE_PRE_HIGHWATERMARK_HOOK = 2; private static final int USE_POST_HIGHWATERMARK_HOOK = 3; private static final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); @Test void testReadSingleCollectionWithSingleParallelism() throws Exception { testMongoDBParallelSource( 1, FailoverType.NONE, FailoverPhase.NEVER, new String[] {"customers"}); } @Test void testReadSingleCollectionWithMultipleParallelism() throws Exception { testMongoDBParallelSource( 4, FailoverType.NONE, FailoverPhase.NEVER, new String[] {"customers"}); } @Test void testReadMultipleCollectionWithSingleParallelism() throws Exception { testMongoDBParallelSource( 1, FailoverType.NONE, FailoverPhase.NEVER, new String[] {"customers", "customers_1"}); } @Test void testReadMultipleCollectionWithMultipleParallelism() throws Exception { testMongoDBParallelSource( 4, FailoverType.NONE, FailoverPhase.NEVER, new String[] {"customers", "customers_1"}); } // Failover tests @Test void testTaskManagerFailoverInSnapshotPhase() throws Exception { testMongoDBParallelSource( FailoverType.TM, FailoverPhase.SNAPSHOT, new String[] {"customers", "customers_1"}); } @Test void testTaskManagerFailoverInStreamPhase() throws Exception { testMongoDBParallelSource( FailoverType.TM, FailoverPhase.STREAM, new String[] {"customers", "customers_1"}); } @Test void testJobManagerFailoverInSnapshotPhase() throws Exception { testMongoDBParallelSource( FailoverType.JM, FailoverPhase.SNAPSHOT, new String[] {"customers", "customers_1"}); } @Test void testJobManagerFailoverInStreamPhase() throws Exception { testMongoDBParallelSource( FailoverType.JM, FailoverPhase.STREAM, new String[] {"customers", "customers_1"}); } @Test void testTaskManagerFailoverSingleParallelism() throws Exception { testMongoDBParallelSource( 1, FailoverType.TM, FailoverPhase.SNAPSHOT, new String[] {"customers"}); } @Test void testJobManagerFailoverSingleParallelism() throws Exception { testMongoDBParallelSource( 1, FailoverType.JM, FailoverPhase.SNAPSHOT, new String[] {"customers"}); } @Test void testReadSingleTableWithSingleParallelismAndSkipBackfill() throws Exception { testMongoDBParallelSource( DEFAULT_PARALLELISM, FailoverType.TM, FailoverPhase.SNAPSHOT, new String[] {"customers"}, true); } @Test void testSnapshotOnlyModeWithDMLPostHighWaterMark() throws Exception { // The data num is 21, set fetchSize = 22 to test whether the job is bounded. List<String> records = testBackfillWhenWritingEvents( false, 22, USE_POST_HIGHWATERMARK_HOOK, StartupOptions.snapshot()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[1019, user_20, Shanghai, 123567891234]", "+I[2000, user_21, Shanghai, 123567891234]"); assertEqualsInAnyOrder(expectedRecords, records); } @Test void testSnapshotOnlyModeWithDMLPreHighWaterMark() throws Exception { // The data num is 21, set fetchSize = 22 to test whether the job is bounded List<String> records = testBackfillWhenWritingEvents( false, 22, USE_PRE_HIGHWATERMARK_HOOK, StartupOptions.snapshot()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[2000, user_21, Pittsburgh, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]"); // when enable backfill, the wal log between (snapshot, high_watermark) will be // applied as snapshot image assertEqualsInAnyOrder(expectedRecords, records); } @Test void testEnableBackfillWithDMLPreHighWaterMark() throws Exception { List<String> records = testBackfillWhenWritingEvents( false, 21, USE_PRE_HIGHWATERMARK_HOOK, StartupOptions.initial()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[2000, user_21, Pittsburgh, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]"); // when enable backfill, the wal log between (snapshot, high_watermark) will be // applied as snapshot image assertEqualsInAnyOrder(expectedRecords, records); } @Test void testEnableBackfillWithDMLPostLowWaterMark() throws Exception { List<String> records = testBackfillWhenWritingEvents( false, 21, USE_POST_LOWWATERMARK_HOOK, StartupOptions.initial()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[2000, user_21, Pittsburgh, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]"); // when enable backfill, the wal log between (low_watermark, snapshot) will be applied // as snapshot image assertEqualsInAnyOrder(expectedRecords, records); } @Test void testEnableBackfillWithDMLPostHighWaterMark() throws Exception { List<String> records = testBackfillWhenWritingEvents( false, 24, USE_POST_HIGHWATERMARK_HOOK, StartupOptions.initial()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[1019, user_20, Shanghai, 123567891234]", "+I[2000, user_21, Shanghai, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]", "+U[2000, user_21, Pittsburgh, 123567891234]", // delete message only contains _id, sql job contain value because of // changelog normalization "-D[0, null, null, null]"); assertEqualsInAnyOrder(expectedRecords, records); } @Test void testSkipBackfillWithDMLPreHighWaterMark() throws Exception { List<String> records = testBackfillWhenWritingEvents( true, 24, USE_PRE_HIGHWATERMARK_HOOK, StartupOptions.initial()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[1019, user_20, Shanghai, 123567891234]", "+I[2000, user_21, Shanghai, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]", "+U[2000, user_21, Pittsburgh, 123567891234]", // delete message only contains _id, sql job contain value because of // changelog normalization "-D[0, null, null, null]"); // when skip backfill, the wal log between (snapshot, high_watermark) will be seen as // stream event. assertEqualsInAnyOrder(expectedRecords, records); } @Test void testSkipBackfillWithDMLPostLowWaterMark() throws Exception { List<String> records = testBackfillWhenWritingEvents( true, 24, USE_POST_LOWWATERMARK_HOOK, StartupOptions.initial()); List<String> expectedRecords = Arrays.asList( "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[2000, user_21, Pittsburgh, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]", "+I[15213, user_15213, Shanghai, 123567891234]", "+U[2000, user_21, Pittsburgh, 123567891234]", // delete message only contains _id, sql job contain value because of // changelog normalization "-D[0, null, null, null]"); // when skip backfill, the wal log between (snapshot, high_watermark) will still be // seen as stream event. This will occur data duplicate. For example, user_20 will be // deleted twice, and user_15213 will be inserted twice. assertEqualsInAnyOrder(expectedRecords, records); } private List<String> testBackfillWhenWritingEvents( boolean skipBackFill, int fetchSize, int hookType, StartupOptions startupOptions) throws Exception { String customerDatabase = MONGO_CONTAINER.executeCommandFileInSeparateDatabase("customer"); env.enableCheckpointing(1000); env.setParallelism(1); ResolvedSchema customersSchema = new ResolvedSchema( Arrays.asList( physical("cid", BIGINT().notNull()), physical("name", STRING()), physical("address", STRING()), physical("phone_number", STRING())), new ArrayList<>(), UniqueConstraint.primaryKey("pk", Collections.singletonList("cid"))); TestTable customerTable = new TestTable(customerDatabase, "customers", customersSchema); MongoDBSource<RowData> source = new MongoDBSourceBuilder<RowData>() .hosts(MONGO_CONTAINER.getHostAndPort()) .databaseList(customerDatabase) .username(FLINK_USER) .password(FLINK_USER_PASSWORD) .startupOptions(StartupOptions.initial()) .scanFullChangelog(false) .collectionList( getCollectionNameRegex( customerDatabase, new String[] {"customers"})) .deserializer(customerTable.getDeserializer(false)) .skipSnapshotBackfill(skipBackFill) .startupOptions(startupOptions) .build(); // Do some database operations during hook in snapshot phase. SnapshotPhaseHooks hooks = new SnapshotPhaseHooks(); SnapshotPhaseHook snapshotPhaseHook = (sourceConfig, split) -> { MongoDBSourceConfig mongoDBSourceConfig = (MongoDBSourceConfig) sourceConfig; MongoClient mongoClient = MongoUtils.clientFor(mongoDBSourceConfig); MongoDatabase database = mongoClient.getDatabase(mongoDBSourceConfig.getDatabaseList().get(0)); MongoCollection<Document> mongoCollection = database.getCollection("customers"); Document document = new Document(); document.put("cid", 15213L); document.put("name", "user_15213"); document.put("address", "Shanghai"); document.put("phone_number", "123567891234"); mongoCollection.insertOne(document); mongoCollection.updateOne( Filters.eq("cid", 2000L), Updates.set("address", "Pittsburgh")); mongoCollection.deleteOne(Filters.eq("cid", 1019L)); // Rarely happens, but if there's no operation or heartbeat events between // watermark #a (the ChangeStream opLog caused by the last event in this hook) // and watermark #b (the calculated high watermark that limits the bounded // back-filling stream fetch task), the last event of hook will be missed since // back-filling task reads between [loW, hiW) (high watermark not included). // Workaround: insert a dummy event in another collection to forcefully push // opLog forward. database.getCollection("customers_1").insertOne(new Document()); }; switch (hookType) { case USE_POST_LOWWATERMARK_HOOK: hooks.setPostLowWatermarkAction(snapshotPhaseHook); break; case USE_PRE_HIGHWATERMARK_HOOK: hooks.setPreHighWatermarkAction(snapshotPhaseHook); break; case USE_POST_HIGHWATERMARK_HOOK: hooks.setPostHighWatermarkAction(snapshotPhaseHook); break; } source.setSnapshotHooks(hooks); List<String> records = new ArrayList<>(); try (CloseableIterator<RowData> iterator = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Backfill Skipped Source") .executeAndCollect()) { records = fetchRowData(iterator, fetchSize, customerTable::stringify); env.close(); } return records; } private void testMongoDBParallelSource( FailoverType failoverType, FailoverPhase failoverPhase, String[] captureCustomerCollections) throws Exception { testMongoDBParallelSource( DEFAULT_PARALLELISM, failoverType, failoverPhase, captureCustomerCollections); } private void testMongoDBParallelSource( int parallelism, FailoverType failoverType, FailoverPhase failoverPhase, String[] captureCustomerCollections) throws Exception { testMongoDBParallelSource( parallelism, failoverType, failoverPhase, captureCustomerCollections, false); } private void testMongoDBParallelSource( int parallelism, FailoverType failoverType, FailoverPhase failoverPhase, String[] captureCustomerCollections, boolean skipSnapshotBackfill) throws Exception { String customerDatabase = MONGO_CONTAINER.executeCommandFileInSeparateDatabase("customer"); StreamTableEnvironment tEnv = StreamTableEnvironment.create(env); env.setParallelism(parallelism); env.enableCheckpointing(200L); env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 0)); String sourceDDL = String.format( "CREATE TABLE customers (" + " _id STRING NOT NULL," + " cid BIGINT NOT NULL," + " name STRING," + " address STRING," + " phone_number STRING," + " primary key (_id) not enforced" + ") WITH (" + " 'connector' = 'mongodb-cdc'," + " 'scan.incremental.snapshot.enabled' = 'true'," + " 'hosts' = '%s'," + " 'username' = '%s'," + " 'password' = '%s'," + " 'database' = '%s'," + " 'collection' = '%s'," + " 'heartbeat.interval.ms' = '500'," + " 'scan.incremental.snapshot.backfill.skip' = '%s'" + ")", MONGO_CONTAINER.getHostAndPort(), FLINK_USER, FLINK_USER_PASSWORD, customerDatabase, getCollectionNameRegex(customerDatabase, captureCustomerCollections), skipSnapshotBackfill); // first step: check the snapshot data String[] snapshotForSingleTable = new String[] { "+I[101, user_1, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "+I[103, user_3, Shanghai, 123567891234]", "+I[109, user_4, Shanghai, 123567891234]", "+I[110, user_5, Shanghai, 123567891234]", "+I[111, user_6, Shanghai, 123567891234]", "+I[118, user_7, Shanghai, 123567891234]", "+I[121, user_8, Shanghai, 123567891234]", "+I[123, user_9, Shanghai, 123567891234]", "+I[1009, user_10, Shanghai, 123567891234]", "+I[1010, user_11, Shanghai, 123567891234]", "+I[1011, user_12, Shanghai, 123567891234]", "+I[1012, user_13, Shanghai, 123567891234]", "+I[1013, user_14, Shanghai, 123567891234]", "+I[1014, user_15, Shanghai, 123567891234]", "+I[1015, user_16, Shanghai, 123567891234]", "+I[1016, user_17, Shanghai, 123567891234]", "+I[1017, user_18, Shanghai, 123567891234]", "+I[1018, user_19, Shanghai, 123567891234]", "+I[1019, user_20, Shanghai, 123567891234]", "+I[2000, user_21, Shanghai, 123567891234]" }; tEnv.executeSql(sourceDDL); TableResult tableResult = tEnv.executeSql("select cid, name, address, phone_number from customers"); CloseableIterator<Row> iterator = tableResult.collect(); JobID jobId = tableResult.getJobClient().get().getJobID(); List<String> expectedSnapshotData = new ArrayList<>(); for (int i = 0; i < captureCustomerCollections.length; i++) { expectedSnapshotData.addAll(Arrays.asList(snapshotForSingleTable)); } // trigger failover after some snapshot splits read finished if (failoverPhase == FailoverPhase.SNAPSHOT && iterator.hasNext()) { triggerFailover( failoverType, jobId, miniClusterResource.get().getMiniCluster(), () -> sleepMs(100)); } assertEqualsInAnyOrder( expectedSnapshotData, fetchRows(iterator, expectedSnapshotData.size())); // second step: check the change stream data for (String collectionName : captureCustomerCollections) { makeFirstPartChangeStreamEvents( mongodbClient.getDatabase(customerDatabase), collectionName); } if (failoverPhase == FailoverPhase.STREAM) { triggerFailover( failoverType, jobId, miniClusterResource.get().getMiniCluster(), () -> sleepMs(200)); } for (String collectionName : captureCustomerCollections) { makeSecondPartChangeStreamEvents( mongodbClient.getDatabase(customerDatabase), collectionName); } String[] changeEventsForSingleTable = new String[] { "-U[101, user_1, Shanghai, 123567891234]", "+U[101, user_1, Hangzhou, 123567891234]", "-D[102, user_2, Shanghai, 123567891234]", "+I[102, user_2, Shanghai, 123567891234]", "-U[103, user_3, Shanghai, 123567891234]", "+U[103, user_3, Hangzhou, 123567891234]", "-U[1010, user_11, Shanghai, 123567891234]", "+U[1010, user_11, Hangzhou, 123567891234]", "+I[2001, user_22, Shanghai, 123567891234]", "+I[2002, user_23, Shanghai, 123567891234]", "+I[2003, user_24, Shanghai, 123567891234]" }; List<String> expectedChangeStreamData = new ArrayList<>(); for (int i = 0; i < captureCustomerCollections.length; i++) { expectedChangeStreamData.addAll(Arrays.asList(changeEventsForSingleTable)); } List<String> actualChangeStreamData = fetchRows(iterator, expectedChangeStreamData.size()); assertEqualsInAnyOrder(expectedChangeStreamData, actualChangeStreamData); tableResult.getJobClient().get().cancel().get(); } private String getCollectionNameRegex(String database, String[] captureCustomerCollections) { checkState(captureCustomerCollections.length > 0); if (captureCustomerCollections.length == 1) { return database + "." + captureCustomerCollections[0]; } else { // pattern that matches multiple collections return Arrays.stream(captureCustomerCollections) .map(coll -> "^(" + database + "." + coll + ")$") .collect(Collectors.joining("|")); } } private void sleepMs(long millis) { try { Thread.sleep(millis); } catch (InterruptedException ignored) { } } private void makeFirstPartChangeStreamEvents(MongoDatabase mongoDatabase, String collection) { MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collection); mongoCollection.updateOne(Filters.eq("cid", 101L), Updates.set("address", "Hangzhou")); mongoCollection.deleteOne(Filters.eq("cid", 102L)); mongoCollection.insertOne(customerDocOf(102L, "user_2", "Shanghai", "123567891234")); mongoCollection.updateOne(Filters.eq("cid", 103L), Updates.set("address", "Hangzhou")); } private void makeSecondPartChangeStreamEvents(MongoDatabase mongoDatabase, String collection) { MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collection); mongoCollection.updateOne(Filters.eq("cid", 1010L), Updates.set("address", "Hangzhou")); mongoCollection.insertMany( Arrays.asList( customerDocOf(2001L, "user_22", "Shanghai", "123567891234"), customerDocOf(2002L, "user_23", "Shanghai", "123567891234"), customerDocOf(2003L, "user_24", "Shanghai", "123567891234"))); } private Document customerDocOf(Long cid, String name, String address, String phoneNumber) { Document document = new Document(); document.put("cid", cid); document.put("name", name); document.put("address", address); document.put("phone_number", phoneNumber); return document; } }
google/j2objc
35,626
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ComparableTimSort.java
/* * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright 2009 Google Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** * This is a near duplicate of {@link TimSort}, modified for use with * arrays of objects that implement {@link Comparable}, instead of using * explicit comparators. * * <p>If you are using an optimizing VM, you may find that ComparableTimSort * offers no performance benefit over TimSort in conjunction with a * comparator that simply returns {@code ((Comparable)first).compareTo(Second)}. * If this is the case, you are better off deleting ComparableTimSort to * eliminate the code duplication. (See Arrays.java for details.) * * @author Josh Bloch */ class ComparableTimSort { /** * This is the minimum sized sequence that will be merged. Shorter * sequences will be lengthened by calling binarySort. If the entire * array is less than this length, no merges will be performed. * * This constant should be a power of two. It was 64 in Tim Peter's C * implementation, but 32 was empirically determined to work better in * this implementation. In the unlikely event that you set this constant * to be a number that's not a power of two, you'll need to change the * {@link #minRunLength} computation. * * If you decrease this constant, you must change the stackLen * computation in the TimSort constructor, or you risk an * ArrayOutOfBounds exception. See listsort.txt for a discussion * of the minimum stack length required as a function of the length * of the array being sorted and the minimum merge sequence length. */ private static final int MIN_MERGE = 32; /** * The array being sorted. */ private final Object[] a; /** * When we get into galloping mode, we stay there until both runs win less * often than MIN_GALLOP consecutive times. */ private static final int MIN_GALLOP = 7; /** * This controls when we get *into* galloping mode. It is initialized * to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for * random data, and lower for highly structured data. */ private int minGallop = MIN_GALLOP; /** * Maximum initial size of tmp array, which is used for merging. The array * can grow to accommodate demand. * * Unlike Tim's original C version, we do not allocate this much storage * when sorting smaller arrays. This change was required for performance. */ private static final int INITIAL_TMP_STORAGE_LENGTH = 256; /** * Temp storage for merges. A workspace array may optionally be * provided in constructor, and if so will be used as long as it * is big enough. */ private Object[] tmp; private int tmpBase; // base of tmp array slice private int tmpLen; // length of tmp array slice /** * A stack of pending runs yet to be merged. Run i starts at * address base[i] and extends for len[i] elements. It's always * true (so long as the indices are in bounds) that: * * runBase[i] + runLen[i] == runBase[i + 1] * * so we could cut the storage for this, but it's a minor amount, * and keeping all the info explicit simplifies the code. */ private int stackSize = 0; // Number of pending runs on stack private final int[] runBase; private final int[] runLen; /** * Creates a TimSort instance to maintain the state of an ongoing sort. * * @param a the array to be sorted * @param work a workspace array (slice) * @param workBase origin of usable space in work array * @param workLen usable size of work array */ private ComparableTimSort(Object[] a, Object[] work, int workBase, int workLen) { this.a = a; // Allocate temp storage (which may be increased later if necessary) int len = a.length; int tlen = (len < 2 * INITIAL_TMP_STORAGE_LENGTH) ? len >>> 1 : INITIAL_TMP_STORAGE_LENGTH; if (work == null || workLen < tlen || workBase + tlen > work.length) { tmp = new Object[tlen]; tmpBase = 0; tmpLen = tlen; } else { tmp = work; tmpBase = workBase; tmpLen = workLen; } /* * Allocate runs-to-be-merged stack (which cannot be expanded). The * stack length requirements are described in listsort.txt. The C * version always uses the same stack length (85), but this was * measured to be too expensive when sorting "mid-sized" arrays (e.g., * 100 elements) in Java. Therefore, we use smaller (but sufficiently * large) stack lengths for smaller arrays. The "magic numbers" in the * computation below must be changed if MIN_MERGE is decreased. See * the MIN_MERGE declaration above for more information. * The maximum value of 49 allows for an array up to length * Integer.MAX_VALUE-4, if array is filled by the worst case stack size * increasing scenario. More explanations are given in section 4 of: * http://envisage-project.eu/wp-content/uploads/2015/02/sorting.pdf */ int stackLen = (len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 24 : 49); runBase = new int[stackLen]; runLen = new int[stackLen]; } /* * The next method (package private and static) constitutes the * entire API of this class. */ /** * Sorts the given range, using the given workspace array slice * for temp storage when possible. This method is designed to be * invoked from public methods (in class Arrays) after performing * any necessary array bounds checks and expanding parameters into * the required forms. * * @param a the array to be sorted * @param lo the index of the first element, inclusive, to be sorted * @param hi the index of the last element, exclusive, to be sorted * @param work a workspace array (slice) * @param workBase origin of usable space in work array * @param workLen usable size of work array * @since 1.8 */ static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen) { assert a != null && lo >= 0 && lo <= hi && hi <= a.length; int nRemaining = hi - lo; if (nRemaining < 2) return; // Arrays of size 0 and 1 are always sorted // If array is small, do a "mini-TimSort" with no merges if (nRemaining < MIN_MERGE) { int initRunLen = countRunAndMakeAscending(a, lo, hi); binarySort(a, lo, hi, lo + initRunLen); return; } /** * March over the array once, left to right, finding natural runs, * extending short natural runs to minRun elements, and merging runs * to maintain stack invariant. */ ComparableTimSort ts = new ComparableTimSort(a, work, workBase, workLen); int minRun = minRunLength(nRemaining); do { // Identify next run int runLen = countRunAndMakeAscending(a, lo, hi); // If run is short, extend to min(minRun, nRemaining) if (runLen < minRun) { int force = nRemaining <= minRun ? nRemaining : minRun; binarySort(a, lo, lo + force, lo + runLen); runLen = force; } // Push run onto pending-run stack, and maybe merge ts.pushRun(lo, runLen); ts.mergeCollapse(); // Advance to find next run lo += runLen; nRemaining -= runLen; } while (nRemaining != 0); // Merge all remaining runs to complete sort assert lo == hi; ts.mergeForceCollapse(); assert ts.stackSize == 1; } /** * Sorts the specified portion of the specified array using a binary * insertion sort. This is the best method for sorting small numbers * of elements. It requires O(n log n) compares, but O(n^2) data * movement (worst case). * * If the initial part of the specified range is already sorted, * this method can take advantage of it: the method assumes that the * elements from index {@code lo}, inclusive, to {@code start}, * exclusive are already sorted. * * @param a the array in which a range is to be sorted * @param lo the index of the first element in the range to be sorted * @param hi the index after the last element in the range to be sorted * @param start the index of the first element in the range that is * not already known to be sorted ({@code lo <= start <= hi}) */ @SuppressWarnings({"fallthrough", "rawtypes", "unchecked"}) private static void binarySort(Object[] a, int lo, int hi, int start) { assert lo <= start && start <= hi; if (start == lo) start++; for ( ; start < hi; start++) { Comparable pivot = (Comparable) a[start]; // Set left (and right) to the index where a[start] (pivot) belongs int left = lo; int right = start; assert left <= right; /* * Invariants: * pivot >= all in [lo, left). * pivot < all in [right, start). */ while (left < right) { int mid = (left + right) >>> 1; if (pivot.compareTo(a[mid]) < 0) right = mid; else left = mid + 1; } assert left == right; /* * The invariants still hold: pivot >= all in [lo, left) and * pivot < all in [left, start), so pivot belongs at left. Note * that if there are elements equal to pivot, left points to the * first slot after them -- that's why this sort is stable. * Slide elements over to make room for pivot. */ int n = start - left; // The number of elements to move // Switch is just an optimization for arraycopy in default case switch (n) { case 2: a[left + 2] = a[left + 1]; case 1: a[left + 1] = a[left]; break; default: System.arraycopy(a, left, a, left + 1, n); } a[left] = pivot; } } /** * Returns the length of the run beginning at the specified position in * the specified array and reverses the run if it is descending (ensuring * that the run will always be ascending when the method returns). * * A run is the longest ascending sequence with: * * a[lo] <= a[lo + 1] <= a[lo + 2] <= ... * * or the longest descending sequence with: * * a[lo] > a[lo + 1] > a[lo + 2] > ... * * For its intended use in a stable mergesort, the strictness of the * definition of "descending" is needed so that the call can safely * reverse a descending sequence without violating stability. * * @param a the array in which a run is to be counted and possibly reversed * @param lo index of the first element in the run * @param hi index after the last element that may be contained in the run. * It is required that {@code lo < hi}. * @return the length of the run beginning at the specified position in * the specified array */ @SuppressWarnings({"unchecked", "rawtypes"}) private static int countRunAndMakeAscending(Object[] a, int lo, int hi) { assert lo < hi; int runHi = lo + 1; if (runHi == hi) return 1; // Find end of run, and reverse range if descending if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0) runHi++; reverseRange(a, lo, runHi); } else { // Ascending while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) >= 0) runHi++; } return runHi - lo; } /** * Reverse the specified range of the specified array. * * @param a the array in which a range is to be reversed * @param lo the index of the first element in the range to be reversed * @param hi the index after the last element in the range to be reversed */ private static void reverseRange(Object[] a, int lo, int hi) { hi--; while (lo < hi) { Object t = a[lo]; a[lo++] = a[hi]; a[hi--] = t; } } /** * Returns the minimum acceptable run length for an array of the specified * length. Natural runs shorter than this will be extended with * {@link #binarySort}. * * Roughly speaking, the computation is: * * If n < MIN_MERGE, return n (it's too small to bother with fancy stuff). * Else if n is an exact power of 2, return MIN_MERGE/2. * Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k * is close to, but strictly less than, an exact power of 2. * * For the rationale, see listsort.txt. * * @param n the length of the array to be sorted * @return the length of the minimum run to be merged */ private static int minRunLength(int n) { assert n >= 0; int r = 0; // Becomes 1 if any 1 bits are shifted off while (n >= MIN_MERGE) { r |= (n & 1); n >>= 1; } return n + r; } /** * Pushes the specified run onto the pending-run stack. * * @param runBase index of the first element in the run * @param runLen the number of elements in the run */ private void pushRun(int runBase, int runLen) { this.runBase[stackSize] = runBase; this.runLen[stackSize] = runLen; stackSize++; } /** * Examines the stack of runs waiting to be merged and merges adjacent runs * until the stack invariants are reestablished: * * 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1] * 2. runLen[i - 2] > runLen[i - 1] * * This method is called each time a new run is pushed onto the stack, * so the invariants are guaranteed to hold for i < stackSize upon * entry to the method. * * Thanks to Stijn de Gouw, Jurriaan Rot, Frank S. de Boer, * Richard Bubel and Reiner Hahnle, this is fixed with respect to * the analysis in "On the Worst-Case Complexity of TimSort" by * Nicolas Auger, Vincent Jug, Cyril Nicaud, and Carine Pivoteau. */ private void mergeCollapse() { while (stackSize > 1) { int n = stackSize - 2; if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1] || n > 1 && runLen[n-2] <= runLen[n] + runLen[n-1]) { if (runLen[n - 1] < runLen[n + 1]) n--; } else if (n < 0 || runLen[n] > runLen[n + 1]) { break; // Invariant is established } mergeAt(n); } } /** * Merges all runs on the stack until only one remains. This method is * called once, to complete the sort. */ private void mergeForceCollapse() { while (stackSize > 1) { int n = stackSize - 2; if (n > 0 && runLen[n - 1] < runLen[n + 1]) n--; mergeAt(n); } } /** * Merges the two runs at stack indices i and i+1. Run i must be * the penultimate or antepenultimate run on the stack. In other words, * i must be equal to stackSize-2 or stackSize-3. * * @param i stack index of the first of the two runs to merge */ @SuppressWarnings("unchecked") private void mergeAt(int i) { assert stackSize >= 2; assert i >= 0; assert i == stackSize - 2 || i == stackSize - 3; int base1 = runBase[i]; int len1 = runLen[i]; int base2 = runBase[i + 1]; int len2 = runLen[i + 1]; assert len1 > 0 && len2 > 0; assert base1 + len1 == base2; /* * Record the length of the combined runs; if i is the 3rd-last * run now, also slide over the last run (which isn't involved * in this merge). The current run (i+1) goes away in any case. */ runLen[i] = len1 + len2; if (i == stackSize - 3) { runBase[i + 1] = runBase[i + 2]; runLen[i + 1] = runLen[i + 2]; } stackSize--; /* * Find where the first element of run2 goes in run1. Prior elements * in run1 can be ignored (because they're already in place). */ int k = gallopRight((Comparable<Object>) a[base2], a, base1, len1, 0); assert k >= 0; base1 += k; len1 -= k; if (len1 == 0) return; /* * Find where the last element of run1 goes in run2. Subsequent elements * in run2 can be ignored (because they're already in place). */ len2 = gallopLeft((Comparable<Object>) a[base1 + len1 - 1], a, base2, len2, len2 - 1); assert len2 >= 0; if (len2 == 0) return; // Merge remaining runs, using tmp array with min(len1, len2) elements if (len1 <= len2) mergeLo(base1, len1, base2, len2); else mergeHi(base1, len1, base2, len2); } /** * Locates the position at which to insert the specified key into the * specified sorted range; if the range contains an element equal to key, * returns the index of the leftmost equal element. * * @param key the key whose insertion point to search for * @param a the array in which to search * @param base the index of the first element in the range * @param len the length of the range; must be > 0 * @param hint the index at which to begin the search, 0 <= hint < n. * The closer hint is to the result, the faster this method will run. * @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k], * pretending that a[b - 1] is minus infinity and a[b + n] is infinity. * In other words, key belongs at index b + k; or in other words, * the first k elements of a should precede key, and the last n - k * should follow it. */ private static int gallopLeft(Comparable<Object> key, Object[] a, int base, int len, int hint) { assert len > 0 && hint >= 0 && hint < len; int lastOfs = 0; int ofs = 1; if (key.compareTo(a[base + hint]) > 0) { // Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs] int maxOfs = len - hint; while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) > 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to base lastOfs += hint; ofs += hint; } else { // key <= a[base + hint] // Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs] final int maxOfs = hint + 1; while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) <= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to base int tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere * to the right of lastOfs but no farther right than ofs. Do a binary * search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs]. */ lastOfs++; while (lastOfs < ofs) { int m = lastOfs + ((ofs - lastOfs) >>> 1); if (key.compareTo(a[base + m]) > 0) lastOfs = m + 1; // a[base + m] < key else ofs = m; // key <= a[base + m] } assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs] return ofs; } /** * Like gallopLeft, except that if the range contains an element equal to * key, gallopRight returns the index after the rightmost equal element. * * @param key the key whose insertion point to search for * @param a the array in which to search * @param base the index of the first element in the range * @param len the length of the range; must be > 0 * @param hint the index at which to begin the search, 0 <= hint < n. * The closer hint is to the result, the faster this method will run. * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] */ private static int gallopRight(Comparable<Object> key, Object[] a, int base, int len, int hint) { assert len > 0 && hint >= 0 && hint < len; int ofs = 1; int lastOfs = 0; if (key.compareTo(a[base + hint]) < 0) { // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs] int maxOfs = hint + 1; while (ofs < maxOfs && key.compareTo(a[base + hint - ofs]) < 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b int tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } else { // a[b + hint] <= key // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs] int maxOfs = len - hint; while (ofs < maxOfs && key.compareTo(a[base + hint + ofs]) >= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b lastOfs += hint; ofs += hint; } assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to * the right of lastOfs but no farther right than ofs. Do a binary * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs]. */ lastOfs++; while (lastOfs < ofs) { int m = lastOfs + ((ofs - lastOfs) >>> 1); if (key.compareTo(a[base + m]) < 0) ofs = m; // key < a[b + m] else lastOfs = m + 1; // a[b + m] <= key } assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs] return ofs; } /** * Merges two adjacent runs in place, in a stable fashion. The first * element of the first run must be greater than the first element of the * second run (a[base1] > a[base2]), and the last element of the first run * (a[base1 + len1-1]) must be greater than all elements of the second run. * * For performance, this method should be called only when len1 <= len2; * its twin, mergeHi should be called if len1 >= len2. (Either method * may be called if len1 == len2.) * * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged * (must be aBase + aLen) * @param len2 length of second run to be merged (must be > 0) */ @SuppressWarnings({"unchecked", "rawtypes"}) private void mergeLo(int base1, int len1, int base2, int len2) { assert len1 > 0 && len2 > 0 && base1 + len1 == base2; // Copy first run into temp array Object[] a = this.a; // For performance Object[] tmp = ensureCapacity(len1); int cursor1 = tmpBase; // Indexes into tmp array int cursor2 = base2; // Indexes int a int dest = base1; // Indexes int a System.arraycopy(a, base1, tmp, cursor1, len1); // Move first element of second run and deal with degenerate cases a[dest++] = a[cursor2++]; if (--len2 == 0) { System.arraycopy(tmp, cursor1, a, dest, len1); return; } if (len1 == 1) { System.arraycopy(a, cursor2, a, dest, len2); a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge return; } int minGallop = this.minGallop; // Use local variable for performance outer: while (true) { int count1 = 0; // Number of times in a row that first run won int count2 = 0; // Number of times in a row that second run won /* * Do the straightforward thing until (if ever) one run starts * winning consistently. */ do { assert len1 > 1 && len2 > 0; if (((Comparable) a[cursor2]).compareTo(tmp[cursor1]) < 0) { a[dest++] = a[cursor2++]; count2++; count1 = 0; if (--len2 == 0) break outer; } else { a[dest++] = tmp[cursor1++]; count1++; count2 = 0; if (--len1 == 1) break outer; } } while ((count1 | count2) < minGallop); /* * One run is winning so consistently that galloping may be a * huge win. So try that, and continue galloping until (if ever) * neither run appears to be winning consistently anymore. */ do { assert len1 > 1 && len2 > 0; count1 = gallopRight((Comparable) a[cursor2], tmp, cursor1, len1, 0); if (count1 != 0) { System.arraycopy(tmp, cursor1, a, dest, count1); dest += count1; cursor1 += count1; len1 -= count1; if (len1 <= 1) // len1 == 1 || len1 == 0 break outer; } a[dest++] = a[cursor2++]; if (--len2 == 0) break outer; count2 = gallopLeft((Comparable) tmp[cursor1], a, cursor2, len2, 0); if (count2 != 0) { System.arraycopy(a, cursor2, a, dest, count2); dest += count2; cursor2 += count2; len2 -= count2; if (len2 == 0) break outer; } a[dest++] = tmp[cursor1++]; if (--len1 == 1) break outer; minGallop--; } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); if (minGallop < 0) minGallop = 0; minGallop += 2; // Penalize for leaving gallop mode } // End of "outer" loop this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field if (len1 == 1) { assert len2 > 0; System.arraycopy(a, cursor2, a, dest, len2); a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge } else if (len1 == 0) { throw new IllegalArgumentException( "Comparison method violates its general contract!"); } else { assert len2 == 0; assert len1 > 1; System.arraycopy(tmp, cursor1, a, dest, len1); } } /** * Like mergeLo, except that this method should be called only if * len1 >= len2; mergeLo should be called if len1 <= len2. (Either method * may be called if len1 == len2.) * * @param base1 index of first element in first run to be merged * @param len1 length of first run to be merged (must be > 0) * @param base2 index of first element in second run to be merged * (must be aBase + aLen) * @param len2 length of second run to be merged (must be > 0) */ @SuppressWarnings({"unchecked", "rawtypes"}) private void mergeHi(int base1, int len1, int base2, int len2) { assert len1 > 0 && len2 > 0 && base1 + len1 == base2; // Copy second run into temp array Object[] a = this.a; // For performance Object[] tmp = ensureCapacity(len2); int tmpBase = this.tmpBase; System.arraycopy(a, base2, tmp, tmpBase, len2); int cursor1 = base1 + len1 - 1; // Indexes into a int cursor2 = tmpBase + len2 - 1; // Indexes into tmp array int dest = base2 + len2 - 1; // Indexes into a // Move last element of first run and deal with degenerate cases a[dest--] = a[cursor1--]; if (--len1 == 0) { System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2); return; } if (len2 == 1) { dest -= len1; cursor1 -= len1; System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); a[dest] = tmp[cursor2]; return; } int minGallop = this.minGallop; // Use local variable for performance outer: while (true) { int count1 = 0; // Number of times in a row that first run won int count2 = 0; // Number of times in a row that second run won /* * Do the straightforward thing until (if ever) one run * appears to win consistently. */ do { assert len1 > 0 && len2 > 1; if (((Comparable) tmp[cursor2]).compareTo(a[cursor1]) < 0) { a[dest--] = a[cursor1--]; count1++; count2 = 0; if (--len1 == 0) break outer; } else { a[dest--] = tmp[cursor2--]; count2++; count1 = 0; if (--len2 == 1) break outer; } } while ((count1 | count2) < minGallop); /* * One run is winning so consistently that galloping may be a * huge win. So try that, and continue galloping until (if ever) * neither run appears to be winning consistently anymore. */ do { assert len1 > 0 && len2 > 1; count1 = len1 - gallopRight((Comparable) tmp[cursor2], a, base1, len1, len1 - 1); if (count1 != 0) { dest -= count1; cursor1 -= count1; len1 -= count1; System.arraycopy(a, cursor1 + 1, a, dest + 1, count1); if (len1 == 0) break outer; } a[dest--] = tmp[cursor2--]; if (--len2 == 1) break outer; count2 = len2 - gallopLeft((Comparable) a[cursor1], tmp, tmpBase, len2, len2 - 1); if (count2 != 0) { dest -= count2; cursor2 -= count2; len2 -= count2; System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2); if (len2 <= 1) break outer; // len2 == 1 || len2 == 0 } a[dest--] = a[cursor1--]; if (--len1 == 0) break outer; minGallop--; } while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP); if (minGallop < 0) minGallop = 0; minGallop += 2; // Penalize for leaving gallop mode } // End of "outer" loop this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field if (len2 == 1) { assert len1 > 0; dest -= len1; cursor1 -= len1; System.arraycopy(a, cursor1 + 1, a, dest + 1, len1); a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge } else if (len2 == 0) { throw new IllegalArgumentException( "Comparison method violates its general contract!"); } else { assert len1 == 0; assert len2 > 0; System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2); } } /** * Ensures that the external array tmp has at least the specified * number of elements, increasing its size if necessary. The size * increases exponentially to ensure amortized linear time complexity. * * @param minCapacity the minimum required capacity of the tmp array * @return tmp, whether or not it grew */ private Object[] ensureCapacity(int minCapacity) { if (tmpLen < minCapacity) { // Compute smallest power of 2 > minCapacity int newSize = -1 >>> Integer.numberOfLeadingZeros(minCapacity); newSize++; if (newSize < 0) // Not bloody likely! newSize = minCapacity; else newSize = Math.min(newSize, a.length >>> 1); @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) Object[] newArray = new Object[newSize]; tmp = newArray; tmpLen = newSize; tmpBase = 0; } return tmp; } }
googleapis/google-cloud-java
35,630
java-discoveryengine/google-cloud-discoveryengine/src/main/java/com/google/cloud/discoveryengine/v1beta/stub/ConversationalSearchServiceStubSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.discoveryengine.v1beta.stub; import static com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceClient.ListConversationsPagedResponse; import static com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceClient.ListSessionsPagedResponse; 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.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.HttpJsonTransportChannel; import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; 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.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.discoveryengine.v1beta.Answer; import com.google.cloud.discoveryengine.v1beta.AnswerQueryRequest; import com.google.cloud.discoveryengine.v1beta.AnswerQueryResponse; import com.google.cloud.discoveryengine.v1beta.Conversation; import com.google.cloud.discoveryengine.v1beta.ConverseConversationRequest; import com.google.cloud.discoveryengine.v1beta.ConverseConversationResponse; import com.google.cloud.discoveryengine.v1beta.CreateConversationRequest; import com.google.cloud.discoveryengine.v1beta.CreateSessionRequest; import com.google.cloud.discoveryengine.v1beta.DeleteConversationRequest; import com.google.cloud.discoveryengine.v1beta.DeleteSessionRequest; import com.google.cloud.discoveryengine.v1beta.GetAnswerRequest; import com.google.cloud.discoveryengine.v1beta.GetConversationRequest; import com.google.cloud.discoveryengine.v1beta.GetSessionRequest; import com.google.cloud.discoveryengine.v1beta.ListConversationsRequest; import com.google.cloud.discoveryengine.v1beta.ListConversationsResponse; import com.google.cloud.discoveryengine.v1beta.ListSessionsRequest; import com.google.cloud.discoveryengine.v1beta.ListSessionsResponse; import com.google.cloud.discoveryengine.v1beta.Session; import com.google.cloud.discoveryengine.v1beta.UpdateConversationRequest; import com.google.cloud.discoveryengine.v1beta.UpdateSessionRequest; 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.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 ConversationalSearchServiceStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (discoveryengine.googleapis.com) and default port (443) are * used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the * [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings) * of converseConversation: * * <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 * ConversationalSearchServiceStubSettings.Builder conversationalSearchServiceSettingsBuilder = * ConversationalSearchServiceStubSettings.newBuilder(); * conversationalSearchServiceSettingsBuilder * .converseConversationSettings() * .setRetrySettings( * conversationalSearchServiceSettingsBuilder * .converseConversationSettings() * .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()); * ConversationalSearchServiceStubSettings conversationalSearchServiceSettings = * conversationalSearchServiceSettingsBuilder.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. */ @BetaApi @Generated("by gapic-generator-java") public class ConversationalSearchServiceStubSettings extends StubSettings<ConversationalSearchServiceStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build(); private final UnaryCallSettings<ConverseConversationRequest, ConverseConversationResponse> converseConversationSettings; private final UnaryCallSettings<CreateConversationRequest, Conversation> createConversationSettings; private final UnaryCallSettings<DeleteConversationRequest, Empty> deleteConversationSettings; private final UnaryCallSettings<UpdateConversationRequest, Conversation> updateConversationSettings; private final UnaryCallSettings<GetConversationRequest, Conversation> getConversationSettings; private final PagedCallSettings< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse> listConversationsSettings; private final UnaryCallSettings<AnswerQueryRequest, AnswerQueryResponse> answerQuerySettings; private final UnaryCallSettings<GetAnswerRequest, Answer> getAnswerSettings; private final UnaryCallSettings<CreateSessionRequest, Session> createSessionSettings; private final UnaryCallSettings<DeleteSessionRequest, Empty> deleteSessionSettings; private final UnaryCallSettings<UpdateSessionRequest, Session> updateSessionSettings; private final UnaryCallSettings<GetSessionRequest, Session> getSessionSettings; private final PagedCallSettings< ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse> listSessionsSettings; private static final PagedListDescriptor< ListConversationsRequest, ListConversationsResponse, Conversation> LIST_CONVERSATIONS_PAGE_STR_DESC = new PagedListDescriptor< ListConversationsRequest, ListConversationsResponse, Conversation>() { @Override public String emptyToken() { return ""; } @Override public ListConversationsRequest injectToken( ListConversationsRequest payload, String token) { return ListConversationsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListConversationsRequest injectPageSize( ListConversationsRequest payload, int pageSize) { return ListConversationsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListConversationsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListConversationsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Conversation> extractResources(ListConversationsResponse payload) { return payload.getConversationsList(); } }; private static final PagedListDescriptor<ListSessionsRequest, ListSessionsResponse, Session> LIST_SESSIONS_PAGE_STR_DESC = new PagedListDescriptor<ListSessionsRequest, ListSessionsResponse, Session>() { @Override public String emptyToken() { return ""; } @Override public ListSessionsRequest injectToken(ListSessionsRequest payload, String token) { return ListSessionsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListSessionsRequest injectPageSize(ListSessionsRequest payload, int pageSize) { return ListSessionsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListSessionsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListSessionsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Session> extractResources(ListSessionsResponse payload) { return payload.getSessionsList(); } }; private static final PagedListResponseFactory< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse> LIST_CONVERSATIONS_PAGE_STR_FACT = new PagedListResponseFactory< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse>() { @Override public ApiFuture<ListConversationsPagedResponse> getFuturePagedResponse( UnaryCallable<ListConversationsRequest, ListConversationsResponse> callable, ListConversationsRequest request, ApiCallContext context, ApiFuture<ListConversationsResponse> futureResponse) { PageContext<ListConversationsRequest, ListConversationsResponse, Conversation> pageContext = PageContext.create( callable, LIST_CONVERSATIONS_PAGE_STR_DESC, request, context); return ListConversationsPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse> LIST_SESSIONS_PAGE_STR_FACT = new PagedListResponseFactory< ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse>() { @Override public ApiFuture<ListSessionsPagedResponse> getFuturePagedResponse( UnaryCallable<ListSessionsRequest, ListSessionsResponse> callable, ListSessionsRequest request, ApiCallContext context, ApiFuture<ListSessionsResponse> futureResponse) { PageContext<ListSessionsRequest, ListSessionsResponse, Session> pageContext = PageContext.create(callable, LIST_SESSIONS_PAGE_STR_DESC, request, context); return ListSessionsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to converseConversation. */ public UnaryCallSettings<ConverseConversationRequest, ConverseConversationResponse> converseConversationSettings() { return converseConversationSettings; } /** Returns the object with the settings used for calls to createConversation. */ public UnaryCallSettings<CreateConversationRequest, Conversation> createConversationSettings() { return createConversationSettings; } /** Returns the object with the settings used for calls to deleteConversation. */ public UnaryCallSettings<DeleteConversationRequest, Empty> deleteConversationSettings() { return deleteConversationSettings; } /** Returns the object with the settings used for calls to updateConversation. */ public UnaryCallSettings<UpdateConversationRequest, Conversation> updateConversationSettings() { return updateConversationSettings; } /** Returns the object with the settings used for calls to getConversation. */ public UnaryCallSettings<GetConversationRequest, Conversation> getConversationSettings() { return getConversationSettings; } /** Returns the object with the settings used for calls to listConversations. */ public PagedCallSettings< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse> listConversationsSettings() { return listConversationsSettings; } /** Returns the object with the settings used for calls to answerQuery. */ public UnaryCallSettings<AnswerQueryRequest, AnswerQueryResponse> answerQuerySettings() { return answerQuerySettings; } /** Returns the object with the settings used for calls to getAnswer. */ public UnaryCallSettings<GetAnswerRequest, Answer> getAnswerSettings() { return getAnswerSettings; } /** Returns the object with the settings used for calls to createSession. */ public UnaryCallSettings<CreateSessionRequest, Session> createSessionSettings() { return createSessionSettings; } /** Returns the object with the settings used for calls to deleteSession. */ public UnaryCallSettings<DeleteSessionRequest, Empty> deleteSessionSettings() { return deleteSessionSettings; } /** Returns the object with the settings used for calls to updateSession. */ public UnaryCallSettings<UpdateSessionRequest, Session> updateSessionSettings() { return updateSessionSettings; } /** Returns the object with the settings used for calls to getSession. */ public UnaryCallSettings<GetSessionRequest, Session> getSessionSettings() { return getSessionSettings; } /** Returns the object with the settings used for calls to listSessions. */ public PagedCallSettings<ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse> listSessionsSettings() { return listSessionsSettings; } public ConversationalSearchServiceStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcConversationalSearchServiceStub.create(this); } if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonConversationalSearchServiceStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "discoveryengine"; } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ @ObsoleteApi("Use getEndpoint() instead") public static String getDefaultEndpoint() { return "discoveryengine.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "discoveryengine.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder() .setScopesToApply(DEFAULT_SERVICE_SCOPES) .setUseJwtAccessWithScope(true); } /** Returns a builder for the default gRPC ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } /** Returns a builder for the default REST ChannelProvider for this service. */ @BetaApi public static InstantiatingHttpJsonChannelProvider.Builder defaultHttpJsonTransportProviderBuilder() { return InstantiatingHttpJsonChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(ConversationalSearchServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(ConversationalSearchServiceStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), GaxHttpJsonProperties.getHttpJsonVersion()); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ConversationalSearchServiceStubSettings.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 ConversationalSearchServiceStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); converseConversationSettings = settingsBuilder.converseConversationSettings().build(); createConversationSettings = settingsBuilder.createConversationSettings().build(); deleteConversationSettings = settingsBuilder.deleteConversationSettings().build(); updateConversationSettings = settingsBuilder.updateConversationSettings().build(); getConversationSettings = settingsBuilder.getConversationSettings().build(); listConversationsSettings = settingsBuilder.listConversationsSettings().build(); answerQuerySettings = settingsBuilder.answerQuerySettings().build(); getAnswerSettings = settingsBuilder.getAnswerSettings().build(); createSessionSettings = settingsBuilder.createSessionSettings().build(); deleteSessionSettings = settingsBuilder.deleteSessionSettings().build(); updateSessionSettings = settingsBuilder.updateSessionSettings().build(); getSessionSettings = settingsBuilder.getSessionSettings().build(); listSessionsSettings = settingsBuilder.listSessionsSettings().build(); } /** Builder for ConversationalSearchServiceStubSettings. */ public static class Builder extends StubSettings.Builder<ConversationalSearchServiceStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder< ConverseConversationRequest, ConverseConversationResponse> converseConversationSettings; private final UnaryCallSettings.Builder<CreateConversationRequest, Conversation> createConversationSettings; private final UnaryCallSettings.Builder<DeleteConversationRequest, Empty> deleteConversationSettings; private final UnaryCallSettings.Builder<UpdateConversationRequest, Conversation> updateConversationSettings; private final UnaryCallSettings.Builder<GetConversationRequest, Conversation> getConversationSettings; private final PagedCallSettings.Builder< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse> listConversationsSettings; private final UnaryCallSettings.Builder<AnswerQueryRequest, AnswerQueryResponse> answerQuerySettings; private final UnaryCallSettings.Builder<GetAnswerRequest, Answer> getAnswerSettings; private final UnaryCallSettings.Builder<CreateSessionRequest, Session> createSessionSettings; private final UnaryCallSettings.Builder<DeleteSessionRequest, Empty> deleteSessionSettings; private final UnaryCallSettings.Builder<UpdateSessionRequest, Session> updateSessionSettings; private final UnaryCallSettings.Builder<GetSessionRequest, Session> getSessionSettings; private final PagedCallSettings.Builder< ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse> listSessionsSettings; 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_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE))); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(1000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelayDuration(Duration.ofMillis(10000L)) .setInitialRpcTimeoutDuration(Duration.ofMillis(30000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(30000L)) .setTotalTimeoutDuration(Duration.ofMillis(30000L)) .build(); definitions.put("retry_policy_1_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); converseConversationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createConversationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteConversationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateConversationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getConversationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); listConversationsSettings = PagedCallSettings.newBuilder(LIST_CONVERSATIONS_PAGE_STR_FACT); answerQuerySettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getAnswerSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createSessionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteSessionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateSessionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); getSessionSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); listSessionsSettings = PagedCallSettings.newBuilder(LIST_SESSIONS_PAGE_STR_FACT); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( converseConversationSettings, createConversationSettings, deleteConversationSettings, updateConversationSettings, getConversationSettings, listConversationsSettings, answerQuerySettings, getAnswerSettings, createSessionSettings, deleteSessionSettings, updateSessionSettings, getSessionSettings, listSessionsSettings); initDefaults(this); } protected Builder(ConversationalSearchServiceStubSettings settings) { super(settings); converseConversationSettings = settings.converseConversationSettings.toBuilder(); createConversationSettings = settings.createConversationSettings.toBuilder(); deleteConversationSettings = settings.deleteConversationSettings.toBuilder(); updateConversationSettings = settings.updateConversationSettings.toBuilder(); getConversationSettings = settings.getConversationSettings.toBuilder(); listConversationsSettings = settings.listConversationsSettings.toBuilder(); answerQuerySettings = settings.answerQuerySettings.toBuilder(); getAnswerSettings = settings.getAnswerSettings.toBuilder(); createSessionSettings = settings.createSessionSettings.toBuilder(); deleteSessionSettings = settings.deleteSessionSettings.toBuilder(); updateSessionSettings = settings.updateSessionSettings.toBuilder(); getSessionSettings = settings.getSessionSettings.toBuilder(); listSessionsSettings = settings.listSessionsSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( converseConversationSettings, createConversationSettings, deleteConversationSettings, updateConversationSettings, getConversationSettings, listConversationsSettings, answerQuerySettings, getAnswerSettings, createSessionSettings, deleteSessionSettings, updateSessionSettings, getSessionSettings, listSessionsSettings); } 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 .converseConversationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .createConversationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .deleteConversationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .updateConversationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .getConversationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .listConversationsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .answerQuerySettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .getAnswerSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .createSessionSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .deleteSessionSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .updateSessionSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .getSessionSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); builder .listSessionsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_1_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_1_params")); 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 converseConversation. */ public UnaryCallSettings.Builder<ConverseConversationRequest, ConverseConversationResponse> converseConversationSettings() { return converseConversationSettings; } /** Returns the builder for the settings used for calls to createConversation. */ public UnaryCallSettings.Builder<CreateConversationRequest, Conversation> createConversationSettings() { return createConversationSettings; } /** Returns the builder for the settings used for calls to deleteConversation. */ public UnaryCallSettings.Builder<DeleteConversationRequest, Empty> deleteConversationSettings() { return deleteConversationSettings; } /** Returns the builder for the settings used for calls to updateConversation. */ public UnaryCallSettings.Builder<UpdateConversationRequest, Conversation> updateConversationSettings() { return updateConversationSettings; } /** Returns the builder for the settings used for calls to getConversation. */ public UnaryCallSettings.Builder<GetConversationRequest, Conversation> getConversationSettings() { return getConversationSettings; } /** Returns the builder for the settings used for calls to listConversations. */ public PagedCallSettings.Builder< ListConversationsRequest, ListConversationsResponse, ListConversationsPagedResponse> listConversationsSettings() { return listConversationsSettings; } /** Returns the builder for the settings used for calls to answerQuery. */ public UnaryCallSettings.Builder<AnswerQueryRequest, AnswerQueryResponse> answerQuerySettings() { return answerQuerySettings; } /** Returns the builder for the settings used for calls to getAnswer. */ public UnaryCallSettings.Builder<GetAnswerRequest, Answer> getAnswerSettings() { return getAnswerSettings; } /** Returns the builder for the settings used for calls to createSession. */ public UnaryCallSettings.Builder<CreateSessionRequest, Session> createSessionSettings() { return createSessionSettings; } /** Returns the builder for the settings used for calls to deleteSession. */ public UnaryCallSettings.Builder<DeleteSessionRequest, Empty> deleteSessionSettings() { return deleteSessionSettings; } /** Returns the builder for the settings used for calls to updateSession. */ public UnaryCallSettings.Builder<UpdateSessionRequest, Session> updateSessionSettings() { return updateSessionSettings; } /** Returns the builder for the settings used for calls to getSession. */ public UnaryCallSettings.Builder<GetSessionRequest, Session> getSessionSettings() { return getSessionSettings; } /** Returns the builder for the settings used for calls to listSessions. */ public PagedCallSettings.Builder< ListSessionsRequest, ListSessionsResponse, ListSessionsPagedResponse> listSessionsSettings() { return listSessionsSettings; } @Override public ConversationalSearchServiceStubSettings build() throws IOException { return new ConversationalSearchServiceStubSettings(this); } } }
googleads/google-ads-java
35,525
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/ShoppingProductOrBuilder.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/resources/shopping_product.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.resources; public interface ShoppingProductOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v19.resources.ShoppingProduct) com.google.protobuf.MessageOrBuilder { /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); /** * <pre> * Output only. The id of the merchant that owns the product. * </pre> * * <code>int64 merchant_center_id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The merchantCenterId. */ long getMerchantCenterId(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v19.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channel. */ int getChannelValue(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v19.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channel. */ com.google.ads.googleads.v19.enums.ProductChannelEnum.ProductChannel getChannel(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The languageCode. */ java.lang.String getLanguageCode(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for languageCode. */ com.google.protobuf.ByteString getLanguageCodeBytes(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The feedLabel. */ java.lang.String getFeedLabel(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for feedLabel. */ com.google.protobuf.ByteString getFeedLabelBytes(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The itemId. */ java.lang.String getItemId(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for itemId. */ com.google.protobuf.ByteString getItemIdBytes(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the multiClientAccountId field is set. */ boolean hasMultiClientAccountId(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The multiClientAccountId. */ long getMultiClientAccountId(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the title field is set. */ boolean hasTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The title. */ java.lang.String getTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for title. */ com.google.protobuf.ByteString getTitleBytes(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the brand field is set. */ boolean hasBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The brand. */ java.lang.String getBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for brand. */ com.google.protobuf.ByteString getBrandBytes(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the priceMicros field is set. */ boolean hasPriceMicros(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The priceMicros. */ long getPriceMicros(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the currencyCode field is set. */ boolean hasCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The currencyCode. */ java.lang.String getCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for currencyCode. */ com.google.protobuf.ByteString getCurrencyCodeBytes(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the channelExclusivity field is set. */ boolean hasChannelExclusivity(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channelExclusivity. */ int getChannelExclusivityValue(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channelExclusivity. */ com.google.ads.googleads.v19.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity getChannelExclusivity(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the condition field is set. */ boolean hasCondition(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for condition. */ int getConditionValue(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The condition. */ com.google.ads.googleads.v19.enums.ProductConditionEnum.ProductCondition getCondition(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the availability field is set. */ boolean hasAvailability(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for availability. */ int getAvailabilityValue(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v19.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The availability. */ com.google.ads.googleads.v19.enums.ProductAvailabilityEnum.ProductAvailability getAvailability(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return A list containing the targetCountries. */ java.util.List<java.lang.String> getTargetCountriesList(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The count of targetCountries. */ int getTargetCountriesCount(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the element to return. * @return The targetCountries at the given index. */ java.lang.String getTargetCountries(int index); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the value to return. * @return The bytes of the targetCountries at the given index. */ com.google.protobuf.ByteString getTargetCountriesBytes(int index); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute0 field is set. */ boolean hasCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute0. */ java.lang.String getCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute0. */ com.google.protobuf.ByteString getCustomAttribute0Bytes(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute1 field is set. */ boolean hasCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute1. */ java.lang.String getCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute1. */ com.google.protobuf.ByteString getCustomAttribute1Bytes(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute2 field is set. */ boolean hasCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute2. */ java.lang.String getCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute2. */ com.google.protobuf.ByteString getCustomAttribute2Bytes(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute3 field is set. */ boolean hasCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute3. */ java.lang.String getCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute3. */ com.google.protobuf.ByteString getCustomAttribute3Bytes(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute4 field is set. */ boolean hasCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute4. */ java.lang.String getCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute4. */ com.google.protobuf.ByteString getCustomAttribute4Bytes(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel1 field is set. */ boolean hasCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel1. */ java.lang.String getCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel1. */ com.google.protobuf.ByteString getCategoryLevel1Bytes(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel2 field is set. */ boolean hasCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel2. */ java.lang.String getCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel2. */ com.google.protobuf.ByteString getCategoryLevel2Bytes(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel3 field is set. */ boolean hasCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel3. */ java.lang.String getCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel3. */ com.google.protobuf.ByteString getCategoryLevel3Bytes(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel4 field is set. */ boolean hasCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel4. */ java.lang.String getCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel4. */ com.google.protobuf.ByteString getCategoryLevel4Bytes(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel5 field is set. */ boolean hasCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel5. */ java.lang.String getCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel5. */ com.google.protobuf.ByteString getCategoryLevel5Bytes(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel1 field is set. */ boolean hasProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel1. */ java.lang.String getProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel1. */ com.google.protobuf.ByteString getProductTypeLevel1Bytes(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel2 field is set. */ boolean hasProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel2. */ java.lang.String getProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel2. */ com.google.protobuf.ByteString getProductTypeLevel2Bytes(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel3 field is set. */ boolean hasProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel3. */ java.lang.String getProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel3. */ com.google.protobuf.ByteString getProductTypeLevel3Bytes(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel4 field is set. */ boolean hasProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel4. */ java.lang.String getProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel4. */ com.google.protobuf.ByteString getProductTypeLevel4Bytes(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel5 field is set. */ boolean hasProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel5. */ java.lang.String getProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel5. */ com.google.protobuf.ByteString getProductTypeLevel5Bytes(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the effectiveMaxCpcMicros field is set. */ boolean hasEffectiveMaxCpcMicros(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The effectiveMaxCpcMicros. */ long getEffectiveMaxCpcMicros(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v19.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ int getStatusValue(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v19.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ com.google.ads.googleads.v19.enums.ProductStatusEnum.ProductStatus getStatus(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<com.google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue> getIssuesList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue getIssues(int index); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ int getIssuesCount(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<? extends com.google.ads.googleads.v19.resources.ShoppingProduct.ProductIssueOrBuilder> getIssuesOrBuilderList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v19.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v19.resources.ShoppingProduct.ProductIssueOrBuilder getIssuesOrBuilder( int index); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the campaign field is set. */ boolean hasCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ java.lang.String getCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ com.google.protobuf.ByteString getCampaignBytes(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the adGroup field is set. */ boolean hasAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ java.lang.String getAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ com.google.protobuf.ByteString getAdGroupBytes(); }
googleads/google-ads-java
35,525
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/ShoppingProductOrBuilder.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/resources/shopping_product.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.resources; public interface ShoppingProductOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v20.resources.ShoppingProduct) com.google.protobuf.MessageOrBuilder { /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); /** * <pre> * Output only. The id of the merchant that owns the product. * </pre> * * <code>int64 merchant_center_id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The merchantCenterId. */ long getMerchantCenterId(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v20.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channel. */ int getChannelValue(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v20.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channel. */ com.google.ads.googleads.v20.enums.ProductChannelEnum.ProductChannel getChannel(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The languageCode. */ java.lang.String getLanguageCode(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for languageCode. */ com.google.protobuf.ByteString getLanguageCodeBytes(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The feedLabel. */ java.lang.String getFeedLabel(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for feedLabel. */ com.google.protobuf.ByteString getFeedLabelBytes(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The itemId. */ java.lang.String getItemId(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for itemId. */ com.google.protobuf.ByteString getItemIdBytes(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the multiClientAccountId field is set. */ boolean hasMultiClientAccountId(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The multiClientAccountId. */ long getMultiClientAccountId(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the title field is set. */ boolean hasTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The title. */ java.lang.String getTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for title. */ com.google.protobuf.ByteString getTitleBytes(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the brand field is set. */ boolean hasBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The brand. */ java.lang.String getBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for brand. */ com.google.protobuf.ByteString getBrandBytes(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the priceMicros field is set. */ boolean hasPriceMicros(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The priceMicros. */ long getPriceMicros(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the currencyCode field is set. */ boolean hasCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The currencyCode. */ java.lang.String getCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for currencyCode. */ com.google.protobuf.ByteString getCurrencyCodeBytes(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the channelExclusivity field is set. */ boolean hasChannelExclusivity(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channelExclusivity. */ int getChannelExclusivityValue(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channelExclusivity. */ com.google.ads.googleads.v20.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity getChannelExclusivity(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the condition field is set. */ boolean hasCondition(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for condition. */ int getConditionValue(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The condition. */ com.google.ads.googleads.v20.enums.ProductConditionEnum.ProductCondition getCondition(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the availability field is set. */ boolean hasAvailability(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for availability. */ int getAvailabilityValue(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v20.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The availability. */ com.google.ads.googleads.v20.enums.ProductAvailabilityEnum.ProductAvailability getAvailability(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return A list containing the targetCountries. */ java.util.List<java.lang.String> getTargetCountriesList(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The count of targetCountries. */ int getTargetCountriesCount(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the element to return. * @return The targetCountries at the given index. */ java.lang.String getTargetCountries(int index); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the value to return. * @return The bytes of the targetCountries at the given index. */ com.google.protobuf.ByteString getTargetCountriesBytes(int index); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute0 field is set. */ boolean hasCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute0. */ java.lang.String getCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute0. */ com.google.protobuf.ByteString getCustomAttribute0Bytes(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute1 field is set. */ boolean hasCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute1. */ java.lang.String getCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute1. */ com.google.protobuf.ByteString getCustomAttribute1Bytes(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute2 field is set. */ boolean hasCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute2. */ java.lang.String getCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute2. */ com.google.protobuf.ByteString getCustomAttribute2Bytes(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute3 field is set. */ boolean hasCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute3. */ java.lang.String getCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute3. */ com.google.protobuf.ByteString getCustomAttribute3Bytes(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute4 field is set. */ boolean hasCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute4. */ java.lang.String getCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute4. */ com.google.protobuf.ByteString getCustomAttribute4Bytes(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel1 field is set. */ boolean hasCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel1. */ java.lang.String getCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel1. */ com.google.protobuf.ByteString getCategoryLevel1Bytes(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel2 field is set. */ boolean hasCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel2. */ java.lang.String getCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel2. */ com.google.protobuf.ByteString getCategoryLevel2Bytes(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel3 field is set. */ boolean hasCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel3. */ java.lang.String getCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel3. */ com.google.protobuf.ByteString getCategoryLevel3Bytes(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel4 field is set. */ boolean hasCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel4. */ java.lang.String getCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel4. */ com.google.protobuf.ByteString getCategoryLevel4Bytes(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel5 field is set. */ boolean hasCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel5. */ java.lang.String getCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel5. */ com.google.protobuf.ByteString getCategoryLevel5Bytes(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel1 field is set. */ boolean hasProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel1. */ java.lang.String getProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel1. */ com.google.protobuf.ByteString getProductTypeLevel1Bytes(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel2 field is set. */ boolean hasProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel2. */ java.lang.String getProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel2. */ com.google.protobuf.ByteString getProductTypeLevel2Bytes(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel3 field is set. */ boolean hasProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel3. */ java.lang.String getProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel3. */ com.google.protobuf.ByteString getProductTypeLevel3Bytes(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel4 field is set. */ boolean hasProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel4. */ java.lang.String getProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel4. */ com.google.protobuf.ByteString getProductTypeLevel4Bytes(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel5 field is set. */ boolean hasProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel5. */ java.lang.String getProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel5. */ com.google.protobuf.ByteString getProductTypeLevel5Bytes(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the effectiveMaxCpcMicros field is set. */ boolean hasEffectiveMaxCpcMicros(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The effectiveMaxCpcMicros. */ long getEffectiveMaxCpcMicros(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v20.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ int getStatusValue(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v20.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ com.google.ads.googleads.v20.enums.ProductStatusEnum.ProductStatus getStatus(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<com.google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue> getIssuesList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue getIssues(int index); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ int getIssuesCount(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<? extends com.google.ads.googleads.v20.resources.ShoppingProduct.ProductIssueOrBuilder> getIssuesOrBuilderList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v20.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v20.resources.ShoppingProduct.ProductIssueOrBuilder getIssuesOrBuilder( int index); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the campaign field is set. */ boolean hasCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ java.lang.String getCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ com.google.protobuf.ByteString getCampaignBytes(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the adGroup field is set. */ boolean hasAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ java.lang.String getAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ com.google.protobuf.ByteString getAdGroupBytes(); }
googleads/google-ads-java
35,525
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/ShoppingProductOrBuilder.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/resources/shopping_product.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.resources; public interface ShoppingProductOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v21.resources.ShoppingProduct) com.google.protobuf.MessageOrBuilder { /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Output only. The resource name of the shopping product. * Shopping product resource names have the form: * * `customers/{customer_id}/shoppingProducts/{merchant_center_id}~{channel}~{language_code}~{feed_label}~{item_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); /** * <pre> * Output only. The id of the merchant that owns the product. * </pre> * * <code>int64 merchant_center_id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The merchantCenterId. */ long getMerchantCenterId(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v21.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channel. */ int getChannelValue(); /** * <pre> * Output only. The product channel describing the locality of the product. * </pre> * * <code>.google.ads.googleads.v21.enums.ProductChannelEnum.ProductChannel channel = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channel. */ com.google.ads.googleads.v21.enums.ProductChannelEnum.ProductChannel getChannel(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The languageCode. */ java.lang.String getLanguageCode(); /** * <pre> * Output only. The language code as provided by the merchant, in BCP 47 * format. * </pre> * * <code>string language_code = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for languageCode. */ com.google.protobuf.ByteString getLanguageCodeBytes(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The feedLabel. */ java.lang.String getFeedLabel(); /** * <pre> * Output only. The product feed label as provided by the merchant. * </pre> * * <code>string feed_label = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for feedLabel. */ com.google.protobuf.ByteString getFeedLabelBytes(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The itemId. */ java.lang.String getItemId(); /** * <pre> * Output only. The item id of the product as provided by the merchant. * </pre> * * <code>string item_id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for itemId. */ com.google.protobuf.ByteString getItemIdBytes(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the multiClientAccountId field is set. */ boolean hasMultiClientAccountId(); /** * <pre> * Output only. The id of the Multi Client Account of the merchant, if * present. * </pre> * * <code>optional int64 multi_client_account_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The multiClientAccountId. */ long getMultiClientAccountId(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the title field is set. */ boolean hasTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The title. */ java.lang.String getTitle(); /** * <pre> * Output only. The title of the product as provided by the merchant. * </pre> * * <code>optional string title = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for title. */ com.google.protobuf.ByteString getTitleBytes(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the brand field is set. */ boolean hasBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The brand. */ java.lang.String getBrand(); /** * <pre> * Output only. The brand of the product as provided by the merchant. * </pre> * * <code>optional string brand = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for brand. */ com.google.protobuf.ByteString getBrandBytes(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the priceMicros field is set. */ boolean hasPriceMicros(); /** * <pre> * Output only. The price of the product in micros as provided by the * merchant, in the currency specified in `currency_code` (e.g. $2.97 is * reported as 2970000). * </pre> * * <code>optional int64 price_micros = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The priceMicros. */ long getPriceMicros(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the currencyCode field is set. */ boolean hasCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The currencyCode. */ java.lang.String getCurrencyCode(); /** * <pre> * Output only. The currency code as provided by the merchant, in ISO 4217 * format. * </pre> * * <code>optional string currency_code = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for currencyCode. */ com.google.protobuf.ByteString getCurrencyCodeBytes(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the channelExclusivity field is set. */ boolean hasChannelExclusivity(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for channelExclusivity. */ int getChannelExclusivityValue(); /** * <pre> * Output only. The channel exclusivity of the product as provided by the * merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity channel_exclusivity = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channelExclusivity. */ com.google.ads.googleads.v21.enums.ProductChannelExclusivityEnum.ProductChannelExclusivity getChannelExclusivity(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the condition field is set. */ boolean hasCondition(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for condition. */ int getConditionValue(); /** * <pre> * Output only. The condition of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductConditionEnum.ProductCondition condition = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The condition. */ com.google.ads.googleads.v21.enums.ProductConditionEnum.ProductCondition getCondition(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the availability field is set. */ boolean hasAvailability(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for availability. */ int getAvailabilityValue(); /** * <pre> * Output only. The availability of the product as provided by the merchant. * </pre> * * <code>optional .google.ads.googleads.v21.enums.ProductAvailabilityEnum.ProductAvailability availability = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The availability. */ com.google.ads.googleads.v21.enums.ProductAvailabilityEnum.ProductAvailability getAvailability(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return A list containing the targetCountries. */ java.util.List<java.lang.String> getTargetCountriesList(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The count of targetCountries. */ int getTargetCountriesCount(); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the element to return. * @return The targetCountries at the given index. */ java.lang.String getTargetCountries(int index); /** * <pre> * Output only. Upper-case two-letter ISO 3166-1 code of the regions where the * product is intended to be shown in ads. * </pre> * * <code>repeated string target_countries = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param index The index of the value to return. * @return The bytes of the targetCountries at the given index. */ com.google.protobuf.ByteString getTargetCountriesBytes(int index); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute0 field is set. */ boolean hasCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute0. */ java.lang.String getCustomAttribute0(); /** * <pre> * Output only. The custom attribute 0 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute0 = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute0. */ com.google.protobuf.ByteString getCustomAttribute0Bytes(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute1 field is set. */ boolean hasCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute1. */ java.lang.String getCustomAttribute1(); /** * <pre> * Output only. The custom attribute 1 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute1 = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute1. */ com.google.protobuf.ByteString getCustomAttribute1Bytes(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute2 field is set. */ boolean hasCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute2. */ java.lang.String getCustomAttribute2(); /** * <pre> * Output only. The custom attribute 2 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute2 = 18 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute2. */ com.google.protobuf.ByteString getCustomAttribute2Bytes(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute3 field is set. */ boolean hasCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute3. */ java.lang.String getCustomAttribute3(); /** * <pre> * Output only. The custom attribute 3 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute3 = 19 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute3. */ com.google.protobuf.ByteString getCustomAttribute3Bytes(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the customAttribute4 field is set. */ boolean hasCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The customAttribute4. */ java.lang.String getCustomAttribute4(); /** * <pre> * Output only. The custom attribute 4 of the product as provided by the * merchant. * </pre> * * <code>optional string custom_attribute4 = 20 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for customAttribute4. */ com.google.protobuf.ByteString getCustomAttribute4Bytes(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel1 field is set. */ boolean hasCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel1. */ java.lang.String getCategoryLevel1(); /** * <pre> * Output only. The category level 1 of the product. * </pre> * * <code>optional string category_level1 = 21 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel1. */ com.google.protobuf.ByteString getCategoryLevel1Bytes(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel2 field is set. */ boolean hasCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel2. */ java.lang.String getCategoryLevel2(); /** * <pre> * Output only. The category level 2 of the product. * </pre> * * <code>optional string category_level2 = 22 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel2. */ com.google.protobuf.ByteString getCategoryLevel2Bytes(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel3 field is set. */ boolean hasCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel3. */ java.lang.String getCategoryLevel3(); /** * <pre> * Output only. The category level 3 of the product. * </pre> * * <code>optional string category_level3 = 23 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel3. */ com.google.protobuf.ByteString getCategoryLevel3Bytes(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel4 field is set. */ boolean hasCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel4. */ java.lang.String getCategoryLevel4(); /** * <pre> * Output only. The category level 4 of the product. * </pre> * * <code>optional string category_level4 = 24 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel4. */ com.google.protobuf.ByteString getCategoryLevel4Bytes(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the categoryLevel5 field is set. */ boolean hasCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The categoryLevel5. */ java.lang.String getCategoryLevel5(); /** * <pre> * Output only. The category level 5 of the product. * </pre> * * <code>optional string category_level5 = 25 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for categoryLevel5. */ com.google.protobuf.ByteString getCategoryLevel5Bytes(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel1 field is set. */ boolean hasProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel1. */ java.lang.String getProductTypeLevel1(); /** * <pre> * Output only. The product type level 1 as provided by the merchant. * </pre> * * <code>optional string product_type_level1 = 26 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel1. */ com.google.protobuf.ByteString getProductTypeLevel1Bytes(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel2 field is set. */ boolean hasProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel2. */ java.lang.String getProductTypeLevel2(); /** * <pre> * Output only. The product type level 2 as provided by the merchant. * </pre> * * <code>optional string product_type_level2 = 27 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel2. */ com.google.protobuf.ByteString getProductTypeLevel2Bytes(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel3 field is set. */ boolean hasProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel3. */ java.lang.String getProductTypeLevel3(); /** * <pre> * Output only. The product type level 3 as provided by the merchant. * </pre> * * <code>optional string product_type_level3 = 28 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel3. */ com.google.protobuf.ByteString getProductTypeLevel3Bytes(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel4 field is set. */ boolean hasProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel4. */ java.lang.String getProductTypeLevel4(); /** * <pre> * Output only. The product type level 4 as provided by the merchant. * </pre> * * <code>optional string product_type_level4 = 29 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel4. */ com.google.protobuf.ByteString getProductTypeLevel4Bytes(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the productTypeLevel5 field is set. */ boolean hasProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The productTypeLevel5. */ java.lang.String getProductTypeLevel5(); /** * <pre> * Output only. The product type level 5 as provided by the merchant. * </pre> * * <code>optional string product_type_level5 = 30 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for productTypeLevel5. */ com.google.protobuf.ByteString getProductTypeLevel5Bytes(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the effectiveMaxCpcMicros field is set. */ boolean hasEffectiveMaxCpcMicros(); /** * <pre> * Output only. The effective maximum cost-per-click (effective max. CPC) of * the product. This field is available only if the query specifies the * campaign or ad group scope, and if the campaign uses manual bidding. The * value is the highest bid set for the product in product groups across all * enabled ad groups. It represents the most you're willing to pay for a click * on the product. This field can take up to 24 hours to update. * </pre> * * <code>optional int64 effective_max_cpc_micros = 31 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The effectiveMaxCpcMicros. */ long getEffectiveMaxCpcMicros(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v21.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ int getStatusValue(); /** * <pre> * Output only. The status that indicates whether the product can show in ads. * The value of this field is restricted to the scope specified in the query, * see the documentation of the resource. * This field can take up to 24 hours to update. * </pre> * * <code>.google.ads.googleads.v21.enums.ProductStatusEnum.ProductStatus status = 32 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ com.google.ads.googleads.v21.enums.ProductStatusEnum.ProductStatus getStatus(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<com.google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue> getIssuesList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue getIssues(int index); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ int getIssuesCount(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<? extends com.google.ads.googleads.v21.resources.ShoppingProduct.ProductIssueOrBuilder> getIssuesOrBuilderList(); /** * <pre> * Output only. The list of issues affecting whether the product can show in * ads. The value of this field is restricted to the scope specified in the * query, see the documentation of the resource. This field can take up to 24 * hours to update. * </pre> * * <code>repeated .google.ads.googleads.v21.resources.ShoppingProduct.ProductIssue issues = 33 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.ads.googleads.v21.resources.ShoppingProduct.ProductIssueOrBuilder getIssuesOrBuilder( int index); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the campaign field is set. */ boolean hasCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The campaign. */ java.lang.String getCampaign(); /** * <pre> * Output only. A campaign that includes the product. * This field is selectable only in the campaign scope, which requires an * equality filter on `campaign`. * </pre> * * <code>optional string campaign = 34 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for campaign. */ com.google.protobuf.ByteString getCampaignBytes(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return Whether the adGroup field is set. */ boolean hasAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ java.lang.String getAdGroup(); /** * <pre> * Output only. An ad group of a campaign that includes the product. * This field is selectable only in the ad group scope, which requires an * equality filter on `campaign` and `ad_group`. * </pre> * * <code>optional string ad_group = 35 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ com.google.protobuf.ByteString getAdGroupBytes(); }
googleapis/google-cloud-java
35,391
java-service-control/proto-google-cloud-service-control-v2/src/main/java/com/google/api/servicecontrol/v2/CheckResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/servicecontrol/v2/service_controller.proto // Protobuf Java Version: 3.25.8 package com.google.api.servicecontrol.v2; /** * * * <pre> * Response message for the Check method. * </pre> * * Protobuf type {@code google.api.servicecontrol.v2.CheckResponse} */ public final class CheckResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.api.servicecontrol.v2.CheckResponse) CheckResponseOrBuilder { private static final long serialVersionUID = 0L; // Use CheckResponse.newBuilder() to construct. private CheckResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CheckResponse() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CheckResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetHeaders(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.servicecontrol.v2.CheckResponse.class, com.google.api.servicecontrol.v2.CheckResponse.Builder.class); } private int bitField0_; public static final int STATUS_FIELD_NUMBER = 1; private com.google.rpc.Status status_; /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> * * @return Whether the status field is set. */ @java.lang.Override public boolean hasStatus() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> * * @return The status. */ @java.lang.Override public com.google.rpc.Status getStatus() { return status_ == null ? com.google.rpc.Status.getDefaultInstance() : status_; } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ @java.lang.Override public com.google.rpc.StatusOrBuilder getStatusOrBuilder() { return status_ == null ? com.google.rpc.Status.getDefaultInstance() : status_; } public static final int HEADERS_FIELD_NUMBER = 2; private static final class HeadersDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance( com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_HeadersEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.String> headers_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetHeaders() { if (headers_ == null) { return com.google.protobuf.MapField.emptyMapField(HeadersDefaultEntryHolder.defaultEntry); } return headers_; } public int getHeadersCount() { return internalGetHeaders().getMap().size(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public boolean containsHeaders(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetHeaders().getMap().containsKey(key); } /** Use {@link #getHeadersMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getHeaders() { return getHeadersMap(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getHeadersMap() { return internalGetHeaders().getMap(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public /* nullable */ java.lang.String getHeadersOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetHeaders().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public java.lang.String getHeadersOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetHeaders().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getStatus()); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetHeaders(), HeadersDefaultEntryHolder.defaultEntry, 2); 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, getStatus()); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetHeaders().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> headers__ = HeadersDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, headers__); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.api.servicecontrol.v2.CheckResponse)) { return super.equals(obj); } com.google.api.servicecontrol.v2.CheckResponse other = (com.google.api.servicecontrol.v2.CheckResponse) obj; if (hasStatus() != other.hasStatus()) return false; if (hasStatus()) { if (!getStatus().equals(other.getStatus())) return false; } if (!internalGetHeaders().equals(other.internalGetHeaders())) 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 (hasStatus()) { hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + getStatus().hashCode(); } if (!internalGetHeaders().getMap().isEmpty()) { hash = (37 * hash) + HEADERS_FIELD_NUMBER; hash = (53 * hash) + internalGetHeaders().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.servicecontrol.v2.CheckResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.api.servicecontrol.v2.CheckResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.servicecontrol.v2.CheckResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.api.servicecontrol.v2.CheckResponse 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 Check method. * </pre> * * Protobuf type {@code google.api.servicecontrol.v2.CheckResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.api.servicecontrol.v2.CheckResponse) com.google.api.servicecontrol.v2.CheckResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 2: return internalGetHeaders(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 2: return internalGetMutableHeaders(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.servicecontrol.v2.CheckResponse.class, com.google.api.servicecontrol.v2.CheckResponse.Builder.class); } // Construct using com.google.api.servicecontrol.v2.CheckResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getStatusFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; status_ = null; if (statusBuilder_ != null) { statusBuilder_.dispose(); statusBuilder_ = null; } internalGetMutableHeaders().clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.api.servicecontrol.v2.ServiceControllerProto .internal_static_google_api_servicecontrol_v2_CheckResponse_descriptor; } @java.lang.Override public com.google.api.servicecontrol.v2.CheckResponse getDefaultInstanceForType() { return com.google.api.servicecontrol.v2.CheckResponse.getDefaultInstance(); } @java.lang.Override public com.google.api.servicecontrol.v2.CheckResponse build() { com.google.api.servicecontrol.v2.CheckResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.api.servicecontrol.v2.CheckResponse buildPartial() { com.google.api.servicecontrol.v2.CheckResponse result = new com.google.api.servicecontrol.v2.CheckResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.api.servicecontrol.v2.CheckResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.status_ = statusBuilder_ == null ? status_ : statusBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.headers_ = internalGetHeaders(); result.headers_.makeImmutable(); } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.api.servicecontrol.v2.CheckResponse) { return mergeFrom((com.google.api.servicecontrol.v2.CheckResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.api.servicecontrol.v2.CheckResponse other) { if (other == com.google.api.servicecontrol.v2.CheckResponse.getDefaultInstance()) return this; if (other.hasStatus()) { mergeStatus(other.getStatus()); } internalGetMutableHeaders().mergeFrom(other.internalGetHeaders()); bitField0_ |= 0x00000002; this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getStatusFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> headers__ = input.readMessage( HeadersDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableHeaders() .getMutableMap() .put(headers__.getKey(), headers__.getValue()); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.rpc.Status status_; private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> statusBuilder_; /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> * * @return Whether the status field is set. */ public boolean hasStatus() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> * * @return The status. */ public com.google.rpc.Status getStatus() { if (statusBuilder_ == null) { return status_ == null ? com.google.rpc.Status.getDefaultInstance() : status_; } else { return statusBuilder_.getMessage(); } } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public Builder setStatus(com.google.rpc.Status value) { if (statusBuilder_ == null) { if (value == null) { throw new NullPointerException(); } status_ = value; } else { statusBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public Builder setStatus(com.google.rpc.Status.Builder builderForValue) { if (statusBuilder_ == null) { status_ = builderForValue.build(); } else { statusBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public Builder mergeStatus(com.google.rpc.Status value) { if (statusBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && status_ != null && status_ != com.google.rpc.Status.getDefaultInstance()) { getStatusBuilder().mergeFrom(value); } else { status_ = value; } } else { statusBuilder_.mergeFrom(value); } if (status_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000001); status_ = null; if (statusBuilder_ != null) { statusBuilder_.dispose(); statusBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public com.google.rpc.Status.Builder getStatusBuilder() { bitField0_ |= 0x00000001; onChanged(); return getStatusFieldBuilder().getBuilder(); } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ public com.google.rpc.StatusOrBuilder getStatusOrBuilder() { if (statusBuilder_ != null) { return statusBuilder_.getMessageOrBuilder(); } else { return status_ == null ? com.google.rpc.Status.getDefaultInstance() : status_; } } /** * * * <pre> * Operation is allowed when this field is not set. Any non-'OK' status * indicates a denial; [google.rpc.Status.details][google.rpc.Status.details] * would contain additional details about the denial. * </pre> * * <code>.google.rpc.Status status = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder> getStatusFieldBuilder() { if (statusBuilder_ == null) { statusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>(getStatus(), getParentForChildren(), isClean()); status_ = null; } return statusBuilder_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> headers_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetHeaders() { if (headers_ == null) { return com.google.protobuf.MapField.emptyMapField(HeadersDefaultEntryHolder.defaultEntry); } return headers_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableHeaders() { if (headers_ == null) { headers_ = com.google.protobuf.MapField.newMapField(HeadersDefaultEntryHolder.defaultEntry); } if (!headers_.isMutable()) { headers_ = headers_.copy(); } bitField0_ |= 0x00000002; onChanged(); return headers_; } public int getHeadersCount() { return internalGetHeaders().getMap().size(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public boolean containsHeaders(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetHeaders().getMap().containsKey(key); } /** Use {@link #getHeadersMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getHeaders() { return getHeadersMap(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getHeadersMap() { return internalGetHeaders().getMap(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public /* nullable */ java.lang.String getHeadersOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetHeaders().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ @java.lang.Override public java.lang.String getHeadersOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetHeaders().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearHeaders() { bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableHeaders().getMutableMap().clear(); return this; } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ public Builder removeHeaders(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableHeaders().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableHeaders() { bitField0_ |= 0x00000002; return internalGetMutableHeaders().getMutableMap(); } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ public Builder putHeaders(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableHeaders().getMutableMap().put(key, value); bitField0_ |= 0x00000002; return this; } /** * * * <pre> * Returns a set of request contexts generated from the `CheckRequest`. * </pre> * * <code>map&lt;string, string&gt; headers = 2;</code> */ public Builder putAllHeaders(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableHeaders().getMutableMap().putAll(values); bitField0_ |= 0x00000002; return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.api.servicecontrol.v2.CheckResponse) } // @@protoc_insertion_point(class_scope:google.api.servicecontrol.v2.CheckResponse) private static final com.google.api.servicecontrol.v2.CheckResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.api.servicecontrol.v2.CheckResponse(); } public static com.google.api.servicecontrol.v2.CheckResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CheckResponse> PARSER = new com.google.protobuf.AbstractParser<CheckResponse>() { @java.lang.Override public CheckResponse 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<CheckResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CheckResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.api.servicecontrol.v2.CheckResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ignite
35,413
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAwareTest.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.processors.cache.persistence.wal.aware; import java.util.concurrent.CountDownLatch; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.logger.NullLogger; import org.junit.Test; import static org.apache.ignite.configuration.DataStorageConfiguration.UNLIMITED_WAL_ARCHIVE; import static org.apache.ignite.testframework.GridTestUtils.getFieldValue; import static org.apache.ignite.testframework.GridTestUtils.runAsync; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test for {@link SegmentAware}. */ public class SegmentAwareTest { /** * Checking to avoid deadlock SegmentArchivedStorage.markAsMovedToArchive -> SegmentLockStorage.locked <-> * SegmentLockStorage.releaseWorkSegment -> SegmentArchivedStorage.onSegmentUnlocked * * @throws IgniteCheckedException if failed. */ @Test public void testAvoidDeadlockArchiverAndLockStorage() throws IgniteCheckedException { SegmentAware aware = segmentAware(10); int iterationCnt = 100_000; int segmentToHandle = 1; IgniteInternalFuture archiverThread = runAsync(() -> { int i = iterationCnt; while (i-- > 0) { try { aware.markAsMovedToArchive(segmentToHandle); } catch (IgniteInterruptedCheckedException e) { throw new RuntimeException(e); } } }); IgniteInternalFuture lockerThread = runAsync(() -> { int i = iterationCnt; while (i-- > 0) { if (aware.lock(segmentToHandle)) aware.unlock(segmentToHandle); } }); archiverThread.get(); lockerThread.get(); } /** * Waiting finished when work segment is set. */ @Test public void testFinishAwaitSegment_WhenExactWaitingSegmentWasSet() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegment(5)); //when: set exact awaiting segment. aware.curAbsWalIdx(5); //then: waiting should finish immediately fut.get(20); } /** * Waiting finished when work segment greater than expected is set. */ @Test public void testFinishAwaitSegment_WhenGreaterThanWaitingSegmentWasSet() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegment(5)); //when: set grater than awaiting segment. aware.curAbsWalIdx(10); //then: waiting should finish immediately fut.get(20); } /** * Waiting finished when work segment is set. */ @Test public void testFinishAwaitSegment_WhenNextSegmentEqualToWaitingOne() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegment(5)); //when: set less than awaiting segment. aware.curAbsWalIdx(4); //then: thread still waiting the segment assertFutureIsNotFinish(fut); //when: trigger next segment. aware.nextAbsoluteSegmentIndex(); //then: waiting should finish immediately fut.get(20); } /** * Waiting finished when interrupt was triggered. */ @Test public void testFinishAwaitSegment_WhenInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegment(5)); //when: interrupt waiting. aware.interrupt(); //then: IgniteInterruptedCheckedException should be throw. assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Waiting finished when next work segment triggered. */ @Test public void testFinishWaitSegmentForArchive_WhenWorkSegmentIncremented() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.curAbsWalIdx(5); aware.setLastArchivedAbsoluteIndex(4); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentForArchivation); //when: next work segment triggered. aware.nextAbsoluteSegmentIndex(); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when work segment is set. */ @Test public void testFinishWaitSegmentForArchive_WhenWorkSegmentGreaterValue() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.curAbsWalIdx(5); aware.setLastArchivedAbsoluteIndex(4); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentForArchivation); //when: set work segment greater than required. aware.curAbsWalIdx(7); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when interrupt was triggered. */ @Test public void testFinishWaitSegmentForArchive_WhenInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.curAbsWalIdx(5); aware.setLastArchivedAbsoluteIndex(4); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentForArchivation); //when: interrupt waiting. aware.interrupt(); //then: IgniteInterruptedCheckedException should be throw. assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Should correct calculate next segment. */ @Test public void testCorrectCalculateNextSegmentIndex() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.curAbsWalIdx(5); //when: request next work segment. long segmentIdx = aware.nextAbsoluteSegmentIndex(); //then: assertThat(segmentIdx, is(6L)); } /** * Waiting finished when segment archived. */ @Test public void testFinishWaitNextAbsoluteIndex_WhenMarkAsArchivedFirstSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(2); aware.curAbsWalIdx(1); aware.setLastArchivedAbsoluteIndex(-1); IgniteInternalFuture fut = awaitThread(aware::nextAbsoluteSegmentIndex); //when: mark first segment as moved. aware.markAsMovedToArchive(0); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when segment archived. */ @Test public void testFinishWaitNextAbsoluteIndex_WhenSetToArchivedFirst() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(2); aware.curAbsWalIdx(1); aware.setLastArchivedAbsoluteIndex(-1); IgniteInternalFuture fut = awaitThread(aware::nextAbsoluteSegmentIndex); //when: mark first segment as moved. aware.setLastArchivedAbsoluteIndex(0); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when force interrupt was triggered. */ @Test public void testFinishWaitNextAbsoluteIndex_WhenOnlyForceInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(2); aware.curAbsWalIdx(2); aware.setLastArchivedAbsoluteIndex(-1); IgniteInternalFuture fut = awaitThread(aware::nextAbsoluteSegmentIndex); //when: interrupt waiting. aware.interrupt(); //then: nothing to happen because nextAbsoluteSegmentIndex is not interrupt by "interrupt" call. assertFutureIsNotFinish(fut); //when: force interrupt waiting. aware.forceInterrupt(); //then: IgniteInterruptedCheckedException should be throw. assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Waiting finished when segment archived. */ @Test public void testFinishSegmentArchived_WhenSetExactWaitingSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegmentArchived(5)); //when: archived exact expected segment. aware.setLastArchivedAbsoluteIndex(5); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when segment archived. */ @Test public void testFinishSegmentArchived_WhenMarkExactWaitingSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegmentArchived(5)); //when: mark exact segment as moved. aware.markAsMovedToArchive(5); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when segment archived. */ @Test public void testFinishSegmentArchived_WhenSetGreaterThanWaitingSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegmentArchived(5)); //when: archived greater than expected segment. aware.setLastArchivedAbsoluteIndex(7); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when segment archived. */ @Test public void testFinishSegmentArchived_WhenMarkGreaterThanWaitingSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegmentArchived(5)); //when: moved greater than expected segment. aware.markAsMovedToArchive(7); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when interrupt was triggered. */ @Test public void testFinishSegmentArchived_WhenInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.curAbsWalIdx(5); aware.setLastArchivedAbsoluteIndex(4); IgniteInternalFuture fut = awaitThread(() -> aware.awaitSegmentArchived(5)); //when: interrupt waiting. aware.interrupt(); //then: IgniteInterruptedCheckedException should be throw. assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Waiting finished when release work segment. */ @Test public void testMarkAsMovedToArchive_WhenReleaseLockedSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); assertTrue(aware.lock(5)); IgniteInternalFuture fut = awaitThread(() -> aware.markAsMovedToArchive(5)); //when: release exact expected work segment. aware.unlock(5); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished and increment archived segment when interrupt was call. */ @Test public void testMarkAsMovedToArchive_WhenInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); assertTrue(aware.lock(5)); IgniteInternalFuture fut = awaitThread(() -> aware.markAsMovedToArchive(5)); //when: interrupt waiting. aware.interrupt(); //then: IgniteInterruptedCheckedException should be throw. assertFalse(fut.get(20) instanceof IgniteInterruptedCheckedException); //and: last archived segment should be changed. assertEquals(5, aware.lastArchivedAbsoluteIndex()); } /** * Waiting finished when segment archived. */ @Test public void testFinishWaitSegmentToCompress_WhenSetLastArchivedSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10, true); aware.onSegmentCompressed(5); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentToCompress); //when: archived expected segment. aware.setLastArchivedAbsoluteIndex(6); //then: waiting should finish immediately. fut.get(20); } /** * Waiting finished when segment archived. */ @Test public void testFinishWaitSegmentToCompress_WhenMarkLastArchivedSegment() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10, true); aware.onSegmentCompressed(5); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentToCompress); //when: marked expected segment. aware.markAsMovedToArchive(6); //then: waiting should finish immediately. fut.get(20); } /** * Next segment for compress based on truncated archive idx. */ @Test public void testCorrectCalculateNextCompressSegment() throws IgniteCheckedException, InterruptedException { SegmentAware aware = segmentAware(10, true); aware.setLastArchivedAbsoluteIndex(6); for (int exp = 0; exp <= 6; exp++) assertEquals(exp, aware.waitNextSegmentToCompress()); } /** * Waiting finished when interrupt was call. */ @Test public void testFinishWaitSegmentToCompress_WhenInterruptWasCall() throws IgniteCheckedException, InterruptedException { //given: thread which awaited segment. SegmentAware aware = segmentAware(10, true); aware.onSegmentCompressed(5); IgniteInternalFuture fut = awaitThread(aware::waitNextSegmentToCompress); //when: interrupt waiting. aware.interrupt(); //then: IgniteInterruptedCheckedException should be throw. assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Tests that {@link SegmentAware#onSegmentCompressed} returns segments in proper order. */ @Test public void testLastCompressedIdxProperOrdering() throws IgniteInterruptedCheckedException { SegmentAware aware = segmentAware(10, true); for (int i = 0; i < 5; i++) { aware.setLastArchivedAbsoluteIndex(i); aware.waitNextSegmentToCompress(); } aware.onSegmentCompressed(0); aware.onSegmentCompressed(4); assertEquals(0, aware.lastCompressedIdx()); aware.onSegmentCompressed(1); assertEquals(1, aware.lastCompressedIdx()); aware.onSegmentCompressed(3); assertEquals(1, aware.lastCompressedIdx()); aware.onSegmentCompressed(2); assertEquals(4, aware.lastCompressedIdx()); } /** * Segment reserve correctly. */ @Test public void testReserveCorrectly() { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); // Set limits. aware.curAbsWalIdx(10); aware.minReserveIndex(0); //when: reserve one segment twice and one segment once. aware.reserve(5); aware.reserve(5); aware.reserve(7); //then: segments greater than minimum should be reserved. assertTrue(aware.reserved(5)); assertTrue(aware.reserved(10)); assertFalse(aware.reserved(4)); //when: release one of twice locked segment. aware.release(5); //then: nothing to change. assertTrue(aware.reserved(5)); assertTrue(aware.reserved(10)); assertFalse(aware.reserved(4)); //when: again release one of twice locked segment. aware.release(5); //then: segments greater than second locked segment should be reserved. assertTrue(aware.reserved(7)); assertTrue(aware.reserved(10)); assertFalse(aware.reserved(5)); assertFalse(aware.reserved(6)); //when: release last segment. aware.release(7); //then: all segments should be released. assertFalse(aware.reserved(7)); assertFalse(aware.reserved(10)); assertFalse(aware.reserved(6)); } /** * Check that there will be no error if a non-reserved segment is released. */ @Test public void testReleaseUnreservedSegment() { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); aware.reserve(5); aware.release(7); } /** * Segment locked correctly. */ @Test public void testReserveWorkSegmentCorrectly() { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); //when: lock one segment twice. assertTrue(aware.lock(5)); assertTrue(aware.lock(5)); //then: exact one segment should locked. assertTrue(aware.locked(5)); assertFalse(aware.locked(6)); assertFalse(aware.locked(4)); //when: release segment once. aware.unlock(5); //then: nothing to change, segment still locked. assertTrue(aware.locked(5)); assertFalse(aware.locked(6)); assertFalse(aware.locked(4)); //when: release segment. aware.unlock(5); //then: all segments should be unlocked. assertFalse(aware.locked(5)); assertFalse(aware.locked(6)); assertFalse(aware.locked(4)); } /** * Should fail when release unlocked segment. */ @Test public void testAssertFail_WhenReleaseUnreservedWorkSegment() { //given: thread which awaited segment. SegmentAware aware = segmentAware(10); assertTrue(aware.lock(5)); try { aware.unlock(7); } catch (AssertionError e) { return; } fail("Should fail with AssertError because this segment have not reserved"); } /** * Check that the reservation border is working correctly. */ @Test public void testReservationBorder() { SegmentAware aware = segmentAware(10); assertTrue(aware.reserve(0)); assertTrue(aware.reserve(1)); assertFalse(aware.minReserveIndex(0)); assertFalse(aware.minReserveIndex(1)); aware.release(0); assertTrue(aware.minReserveIndex(0)); assertFalse(aware.minReserveIndex(1)); assertFalse(aware.reserve(0)); assertTrue(aware.reserve(1)); } /** * Check that the lock border is working correctly. */ @Test public void testLockBorder() { SegmentAware aware = segmentAware(10); assertTrue(aware.lock(0)); assertTrue(aware.lock(1)); assertFalse(aware.minLockIndex(0)); assertFalse(aware.minLockIndex(1)); aware.unlock(0); assertTrue(aware.minLockIndex(0)); assertFalse(aware.minLockIndex(1)); assertFalse(aware.lock(0)); assertTrue(aware.lock(1)); } /** * Checking the correctness of WAL archive size. * * @throws Exception If failed. */ @Test public void testWalArchiveSize() throws Exception { SegmentAware aware = segmentAware(10); IgniteInternalFuture<?> fut = awaitThread(() -> aware.awaitExceedMaxArchiveSize(10)); aware.addSize(0, 4); assertFutureIsNotFinish(fut); aware.addSize(0, 4); assertFutureIsNotFinish(fut); aware.addSize(0, 4); fut.get(20); aware.resetWalArchiveSizes(); fut = awaitThread(() -> aware.awaitExceedMaxArchiveSize(10)); aware.addSize(1, 4); assertFutureIsNotFinish(fut); aware.addSize(1, 4); assertFutureIsNotFinish(fut); aware.addSize(1, 4); fut.get(20); aware.resetWalArchiveSizes(); fut = awaitThread(() -> aware.awaitExceedMaxArchiveSize(10)); aware.interrupt(); assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); aware.reset(); fut = awaitThread(() -> aware.awaitExceedMaxArchiveSize(10)); aware.forceInterrupt(); assertTrue(fut.get(20) instanceof IgniteInterruptedCheckedException); } /** * Checking the correctness of truncate logic. * * @throws Exception If failed. */ @Test public void testTruncate() throws Exception { SegmentAware aware = segmentAware(10); IgniteInternalFuture<?> fut = awaitThread(aware::awaitAvailableTruncateArchive); aware.lastCheckpointIdx(5); fut.get(20); assertEquals(5, aware.awaitAvailableTruncateArchive()); aware.reserve(4); assertEquals(4, aware.awaitAvailableTruncateArchive()); aware.setLastArchivedAbsoluteIndex(3); assertEquals(3, aware.awaitAvailableTruncateArchive()); aware.lastTruncatedArchiveIdx(0); assertEquals(2, aware.awaitAvailableTruncateArchive()); assertEquals(0, aware.lastTruncatedArchiveIdx()); aware.reserve(0); fut = awaitThread(aware::awaitAvailableTruncateArchive); aware.release(0); fut.get(20); assertEquals(2, aware.awaitAvailableTruncateArchive()); aware.setLastArchivedAbsoluteIndex(4); assertEquals(3, aware.awaitAvailableTruncateArchive()); aware.release(4); assertEquals(3, aware.awaitAvailableTruncateArchive()); aware.lastCheckpointIdx(6); assertEquals(3, aware.awaitAvailableTruncateArchive()); aware.setLastArchivedAbsoluteIndex(6); assertEquals(5, aware.awaitAvailableTruncateArchive()); } /** * Checking the correct calculation of the WAL archive size for an unlimited WAL archive. */ @Test public void testArchiveSizeForUnlimitedWalArchive() { SegmentAware aware = segmentAware(1, false, 0, UNLIMITED_WAL_ARCHIVE); SegmentArchiveSizeStorage sizeStorage = archiveSizeStorage(aware); aware.addSize(0, 10); assertEquals(10, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); aware.addSize(0, 20); assertEquals(30, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); aware.addSize(1, 10); assertEquals(40, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertNull(sizeStorage.segmentSize(1)); aware.addSize(0, -10); assertEquals(30, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertNull(sizeStorage.segmentSize(1)); aware.addSize(1, -10); assertEquals(20, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertNull(sizeStorage.segmentSize(1)); aware.addSize(0, -20); assertEquals(0, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertNull(sizeStorage.segmentSize(1)); } /** * Checking the correct calculation of the WAL archive size for a limited WAL archive. */ @Test public void testArchiveSizeForLimitedWalArchive() { SegmentAware aware = segmentAware(1, false, 100, 200); SegmentArchiveSizeStorage sizeStorage = archiveSizeStorage(aware); aware.addSize(0, 10); assertEquals(10, sizeStorage.currentSize()); assertEquals(Long.valueOf(10), sizeStorage.segmentSize(0)); aware.addSize(0, 20); assertEquals(30, sizeStorage.currentSize()); assertEquals(Long.valueOf(30), sizeStorage.segmentSize(0)); aware.addSize(1, 5); assertEquals(35, sizeStorage.currentSize()); assertEquals(Long.valueOf(30), sizeStorage.segmentSize(0)); assertEquals(Long.valueOf(5), sizeStorage.segmentSize(1)); aware.addSize(0, -5); assertEquals(30, sizeStorage.currentSize()); assertEquals(Long.valueOf(25), sizeStorage.segmentSize(0)); assertEquals(Long.valueOf(5), sizeStorage.segmentSize(1)); aware.addSize(0, -10); assertEquals(20, sizeStorage.currentSize()); assertEquals(Long.valueOf(15), sizeStorage.segmentSize(0)); assertEquals(Long.valueOf(5), sizeStorage.segmentSize(1)); aware.addSize(1, -3); assertEquals(17, sizeStorage.currentSize()); assertEquals(Long.valueOf(15), sizeStorage.segmentSize(0)); assertEquals(Long.valueOf(2), sizeStorage.segmentSize(1)); aware.addSize(0, -15); assertEquals(2, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertEquals(Long.valueOf(2), sizeStorage.segmentSize(1)); aware.addSize(1, -2); assertEquals(0, sizeStorage.currentSize()); assertNull(sizeStorage.segmentSize(0)); assertNull(sizeStorage.segmentSize(1)); } /** * Checking that when the {@code SegmentArchiveSizeStorage#maxWalArchiveSize} is reached, * the segments will be released to the {@code SegmentArchiveSizeStorage#minWalArchiveSize}, * and it will also not be possible to reserve them. */ @Test public void testReleaseSegmentsOnExceedMaxWalArchiveSize() { SegmentAware aware = segmentAware(1, false, 50, 100); SegmentReservationStorage reservationStorage = reservationStorage(aware); aware.startAutoReleaseSegments(); for (int i = 0; i < 9; i++) aware.addSize(i, 10); assertTrue(aware.reserve(0)); assertTrue(aware.reserve(1)); assertTrue(aware.reserve(8)); aware.lastCheckpointIdx(1); aware.addSize(9, 10); assertFalse(aware.reserved(0)); assertFalse(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(1, reservationStorage.minReserveIdx()); aware.lastCheckpointIdx(5); aware.startAutoReleaseSegments(); assertFalse(aware.reserved(0)); assertFalse(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(5, reservationStorage.minReserveIdx()); for (int i = 0; i <= 5; i++) { assertFalse(aware.reserve(i)); assertFalse(aware.reserved(i)); assertTrue(aware.minReserveIndex(i)); } for (int i = 6; i < 10; i++) { assertTrue(aware.reserve(i)); assertFalse(aware.minReserveIndex(i)); } } /** * Check that if the size of the segments does not reach the {@code SegmentArchiveSizeStorage#maxWalArchiveSize} * then there will be no release of the segments. */ @Test public void testNoReleaseSegmentNearMaxWalArchiveSize() { SegmentAware aware = segmentAware(1, false, 50, 100); for (int i = 0; i < 9; i++) aware.addSize(i, 10); assertTrue(aware.reserve(0)); assertTrue(aware.reserve(1)); assertTrue(aware.reserve(8)); aware.addSize(9, 9); assertTrue(aware.reserve(0)); assertTrue(aware.reserve(1)); assertTrue(aware.reserve(8)); } /** * Checking that when the {@code SegmentArchiveSizeStorage#maxWalArchiveSize} is reached * and after calling the {@link SegmentAware#startAutoReleaseSegments()} * the segments will be released to the {@code SegmentArchiveSizeStorage#minWalArchiveSize}, * and it will also not be possible to reserve them. */ @Test public void testReleaseSegmentsOnExceedMaxWalArchiveSizeAfterStartAutoReleaseSegments() { SegmentAware aware = segmentAware(1, false, 50, 100); SegmentReservationStorage reservationStorage = reservationStorage(aware); for (int i = 0; i < 9; i++) aware.addSize(i, 10); assertTrue(aware.reserve(0)); assertTrue(aware.reserve(1)); assertTrue(aware.reserve(8)); aware.addSize(9, 10); assertTrue(aware.reserved(0)); assertTrue(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(-1, reservationStorage.minReserveIdx()); aware.startAutoReleaseSegments(); assertTrue(aware.reserved(0)); assertTrue(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(-1, reservationStorage.minReserveIdx()); aware.lastCheckpointIdx(0); aware.startAutoReleaseSegments(); assertFalse(aware.reserved(0)); assertTrue(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(0, reservationStorage.minReserveIdx()); aware.lastCheckpointIdx(100); aware.startAutoReleaseSegments(); assertFalse(aware.reserved(0)); assertFalse(aware.reserved(1)); assertTrue(aware.reserved(8)); assertEquals(5, reservationStorage.minReserveIdx()); for (int i = 0; i <= 5; i++) { assertFalse(aware.reserve(i)); assertFalse(aware.reserved(i)); assertTrue(aware.minReserveIndex(i)); } for (int i = 6; i < 10; i++) { assertTrue(aware.reserve(i)); assertFalse(aware.minReserveIndex(i)); } } /** * Assert that future is still not finished. * * @param future Future to check. */ private void assertFutureIsNotFinish(IgniteInternalFuture future) throws IgniteCheckedException { try { future.get(20); fail("Timeout should be appear because thread should be still work"); } catch (IgniteFutureTimeoutCheckedException ignore) { } } /** * Create thread for execute waiter. * * @param waiter Waiter for execute in new thread. * @return Future of thread. */ private IgniteInternalFuture awaitThread(Waiter waiter) throws IgniteCheckedException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); IgniteInternalFuture<Object> fut = runAsync( () -> { latch.countDown(); try { waiter.await(); } catch (IgniteInterruptedCheckedException e) { return e; } return null; } ); latch.await(); assertFutureIsNotFinish(fut); return fut; } /** * Represent of command for waiting. */ interface Waiter { /** * Some waiting operation. */ void await() throws IgniteInterruptedCheckedException; } /** * Factory method for the {@link SegmentAware}. * * @param walSegmentsCnt Total WAL segments count. * @return New instance. */ private SegmentAware segmentAware(int walSegmentsCnt) { return segmentAware(walSegmentsCnt, false); } /** * Factory method for the {@link SegmentAware}. * * @param walSegmentsCnt Total WAL segments count. * @param compactionEnabled Is wal compaction enabled. * @return New instance. */ private SegmentAware segmentAware(int walSegmentsCnt, boolean compactionEnabled) { return segmentAware(walSegmentsCnt, compactionEnabled, UNLIMITED_WAL_ARCHIVE, UNLIMITED_WAL_ARCHIVE); } /** * Factory method for the {@link SegmentAware}. * * @param walSegmentsCnt Total WAL segments count. * @param compactionEnabled Is wal compaction enabled. * @param minWalArchiveSize Minimum size of the WAL archive in bytes * or {@link DataStorageConfiguration#UNLIMITED_WAL_ARCHIVE}. * @param maxWalArchiveSize Maximum size of the WAL archive in bytes * or {@link DataStorageConfiguration#UNLIMITED_WAL_ARCHIVE}. * @return New instance. */ private SegmentAware segmentAware( int walSegmentsCnt, boolean compactionEnabled, long minWalArchiveSize, long maxWalArchiveSize ) { return new SegmentAware( new NullLogger(), walSegmentsCnt, compactionEnabled, minWalArchiveSize, maxWalArchiveSize ); } /** * Getting {@code SegmentAware#archiveSizeStorage}. * * @param aware Segment aware. * @return Instance of {@link SegmentArchiveSizeStorage}. */ private SegmentArchiveSizeStorage archiveSizeStorage(SegmentAware aware) { return getFieldValue(aware, "archiveSizeStorage"); } /** * Getting {@code SegmentAware#reservationStorage}. * * @param aware Segment aware. * @return Instance of {@link SegmentReservationStorage}. */ private SegmentReservationStorage reservationStorage(SegmentAware aware) { return getFieldValue(aware, "reservationStorage"); } }
apache/lucene
35,106
lucene/core/src/test/org/apache/lucene/index/TestTermsEnum.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.index; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.store.Directory; import org.apache.lucene.tests.analysis.MockAnalyzer; import org.apache.lucene.tests.index.PerThreadPKLookup; import org.apache.lucene.tests.index.RandomIndexWriter; import org.apache.lucene.tests.util.LineFileDocs; import org.apache.lucene.tests.util.LuceneTestCase; import org.apache.lucene.tests.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.tests.util.TestUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.automaton.Automata; import org.apache.lucene.util.automaton.Automaton; import org.apache.lucene.util.automaton.CompiledAutomaton; import org.apache.lucene.util.automaton.Operations; import org.apache.lucene.util.automaton.RegExp; @SuppressCodecs({"SimpleText", "Direct"}) public class TestTermsEnum extends LuceneTestCase { public void test() throws Exception { Random random = new Random(random().nextLong()); final LineFileDocs docs = new LineFileDocs(random); final Directory d = newDirectory(); MockAnalyzer analyzer = new MockAnalyzer(random()); analyzer.setMaxTokenLength(TestUtil.nextInt(random(), 1, IndexWriter.MAX_TERM_LENGTH)); final RandomIndexWriter w = new RandomIndexWriter(random(), d, analyzer); final int numDocs = atLeast(10); for (int docCount = 0; docCount < numDocs; docCount++) { w.addDocument(docs.nextDoc()); } final IndexReader r = w.getReader(); w.close(); final List<BytesRef> terms = new ArrayList<>(); final TermsEnum termsEnum = MultiTerms.getTerms(r, "body").iterator(); BytesRef term; while ((term = termsEnum.next()) != null) { terms.add(BytesRef.deepCopyOf(term)); } if (VERBOSE) { System.out.println("TEST: " + terms.size() + " terms"); } int upto = -1; final int iters = atLeast(200); for (int iter = 0; iter < iters; iter++) { final boolean isEnd; if (upto != -1 && random().nextBoolean()) { // next if (VERBOSE) { System.out.println("TEST: iter next"); } isEnd = termsEnum.next() == null; upto++; if (isEnd) { if (VERBOSE) { System.out.println(" end"); } assertEquals(upto, terms.size()); upto = -1; } else { if (VERBOSE) { System.out.println( " got term=" + termsEnum.term().utf8ToString() + " expected=" + terms.get(upto).utf8ToString()); } assertTrue(upto < terms.size()); assertEquals(terms.get(upto), termsEnum.term()); } } else { final BytesRef target; final String exists; if (random().nextBoolean()) { // likely fake term if (random().nextBoolean()) { target = newBytesRef(TestUtil.randomSimpleString(random())); } else { target = newBytesRef(TestUtil.randomRealisticUnicodeString(random())); } exists = "likely not"; } else { // real term target = terms.get(random().nextInt(terms.size())); exists = "yes"; } upto = Collections.binarySearch(terms, target); if (random().nextBoolean()) { if (VERBOSE) { System.out.println( "TEST: iter seekCeil target=" + target.utf8ToString() + " exists=" + exists); } // seekCeil final TermsEnum.SeekStatus status = termsEnum.seekCeil(target); if (VERBOSE) { System.out.println(" got " + status); } if (upto < 0) { upto = -(upto + 1); if (upto >= terms.size()) { assertEquals(TermsEnum.SeekStatus.END, status); upto = -1; } else { assertEquals(TermsEnum.SeekStatus.NOT_FOUND, status); assertEquals(terms.get(upto), termsEnum.term()); } } else { assertEquals(TermsEnum.SeekStatus.FOUND, status); assertEquals(terms.get(upto), termsEnum.term()); } } else { if (VERBOSE) { System.out.println( "TEST: iter seekExact target=" + target.utf8ToString() + " exists=" + exists); } // seekExact final boolean result = termsEnum.seekExact(target); if (VERBOSE) { System.out.println(" got " + result); } if (upto < 0) { assertFalse(result); upto = -1; } else { assertTrue(result); assertEquals(target, termsEnum.term()); } } } } r.close(); d.close(); docs.close(); } private void addDoc( RandomIndexWriter w, Collection<String> terms, Map<BytesRef, Integer> termToID, int id) throws IOException { Document doc = new Document(); doc.add(new NumericDocValuesField("id", id)); if (VERBOSE) { System.out.println("TEST: addDoc id:" + id + " terms=" + terms); } for (String s2 : terms) { doc.add(newStringField("f", s2, Field.Store.NO)); termToID.put(newBytesRef(s2), id); } w.addDocument(doc); terms.clear(); } private boolean accepts(CompiledAutomaton c, BytesRef b) { int state = 0; for (int idx = 0; idx < b.length; idx++) { assertTrue(state != -1); state = c.runAutomaton.step(state, b.bytes[b.offset + idx] & 0xff); } return c.runAutomaton.isAccept(state); } // Tests Terms.intersect public void testIntersectRandom() throws IOException { final Directory dir = newDirectory(); final RandomIndexWriter w = new RandomIndexWriter(random(), dir); final int numTerms = atLeast(300); // final int numTerms = 50; final Set<String> terms = new HashSet<>(); final Collection<String> pendingTerms = new ArrayList<>(); final Map<BytesRef, Integer> termToID = new HashMap<>(); int id = 0; while (terms.size() != numTerms) { final String s = getRandomString(); if (!terms.contains(s)) { terms.add(s); pendingTerms.add(s); if (random().nextInt(20) == 7) { addDoc(w, pendingTerms, termToID, id++); } } } addDoc(w, pendingTerms, termToID, id++); final BytesRef[] termsArray = new BytesRef[terms.size()]; final Set<BytesRef> termsSet = new HashSet<>(); { int upto = 0; for (String s : terms) { final BytesRef b = newBytesRef(s); termsArray[upto++] = b; termsSet.add(b); } Arrays.sort(termsArray); } if (VERBOSE) { System.out.println("\nTEST: indexed terms (unicode order):"); for (BytesRef t : termsArray) { System.out.println(" " + t.utf8ToString() + " -> id:" + termToID.get(t)); } } final IndexReader r = w.getReader(); w.close(); int[] docIDToID = new int[r.maxDoc()]; NumericDocValues values = MultiDocValues.getNumericValues(r, "id"); for (int i = 0; i < r.maxDoc(); i++) { assertEquals(i, values.nextDoc()); docIDToID[i] = (int) values.longValue(); } int numIterations = atLeast(3); for (int iter = 0; iter < numIterations; iter++) { // TODO: can we also test infinite As here...? // From the random terms, pick some ratio and compile an // automaton: final Set<String> acceptTerms = new HashSet<>(); final TreeSet<BytesRef> sortedAcceptTerms = new TreeSet<>(); final double keepPct = random().nextDouble(); Automaton a; if (iter == 0) { if (VERBOSE) { System.out.println("\nTEST: empty automaton"); } a = Automata.makeEmpty(); } else { if (VERBOSE) { System.out.println("\nTEST: keepPct=" + keepPct); } for (String s : terms) { final String s2; if (random().nextDouble() <= keepPct) { s2 = s; } else { s2 = getRandomString(); } acceptTerms.add(s2); sortedAcceptTerms.add(newBytesRef(s2)); } a = Automata.makeStringUnion(sortedAcceptTerms); } final CompiledAutomaton c = new CompiledAutomaton(a, true, false, false); final BytesRef[] acceptTermsArray = new BytesRef[acceptTerms.size()]; final Set<BytesRef> acceptTermsSet = new HashSet<>(); int upto = 0; for (String s : acceptTerms) { final BytesRef b = newBytesRef(s); acceptTermsArray[upto++] = b; acceptTermsSet.add(b); assertTrue(accepts(c, b)); } Arrays.sort(acceptTermsArray); if (VERBOSE) { System.out.println("\nTEST: accept terms (unicode order):"); for (BytesRef t : acceptTermsArray) { System.out.println(" " + t.utf8ToString() + (termsSet.contains(t) ? " (exists)" : "")); } System.out.println(a.toDot()); } for (int iter2 = 0; iter2 < 100; iter2++) { final BytesRef startTerm = acceptTermsArray.length == 0 || random().nextBoolean() ? null : acceptTermsArray[random().nextInt(acceptTermsArray.length)]; if (VERBOSE) { System.out.println( "\nTEST: iter2=" + iter2 + " startTerm=" + (startTerm == null ? "<null>" : startTerm.utf8ToString())); if (startTerm != null) { int state = 0; for (int idx = 0; idx < startTerm.length; idx++) { final int label = startTerm.bytes[startTerm.offset + idx] & 0xff; System.out.println(" state=" + state + " label=" + label); state = c.runAutomaton.step(state, label); assertTrue(state != -1); } System.out.println(" state=" + state); } } final TermsEnum te = MultiTerms.getTerms(r, "f").intersect(c, startTerm); int loc; if (startTerm == null) { loc = 0; } else { loc = Arrays.binarySearch(termsArray, BytesRef.deepCopyOf(startTerm)); if (loc < 0) { loc = -(loc + 1); } else { // startTerm exists in index loc++; } } while (loc < termsArray.length && !acceptTermsSet.contains(termsArray[loc])) { loc++; } PostingsEnum postingsEnum = null; while (loc < termsArray.length) { final BytesRef expected = termsArray[loc]; final BytesRef actual = te.next(); if (VERBOSE) { System.out.println( "TEST: next() expected=" + expected.utf8ToString() + " actual=" + (actual == null ? "null" : actual.utf8ToString())); } assertEquals(expected, actual); assertEquals(1, te.docFreq()); postingsEnum = TestUtil.docs(random(), te, postingsEnum, PostingsEnum.NONE); final int docID = postingsEnum.nextDoc(); assertTrue(docID != DocIdSetIterator.NO_MORE_DOCS); assertEquals(docIDToID[docID], termToID.get(expected).intValue()); do { loc++; } while (loc < termsArray.length && !acceptTermsSet.contains(termsArray[loc])); } assertNull(te.next()); } } r.close(); dir.close(); } private Directory d; private IndexReader r; private final String FIELD = "field"; private IndexReader makeIndex(String... terms) throws Exception { d = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); /* iwc.setCodec(new StandardCodec(minTermsInBlock, maxTermsInBlock)); */ final RandomIndexWriter w = new RandomIndexWriter(random(), d, iwc); for (String term : terms) { Document doc = new Document(); Field f = newStringField(FIELD, term, Field.Store.NO); doc.add(f); w.addDocument(doc); } if (r != null) { close(); } r = w.getReader(); w.close(); return r; } private void close() throws Exception { r.close(); d.close(); } private int docFreq(IndexReader r, String term) throws Exception { return r.docFreq(new Term(FIELD, term)); } public void testEasy() throws Exception { // No floor arcs: r = makeIndex("aa0", "aa1", "aa2", "aa3", "bb0", "bb1", "bb2", "bb3", "aa"); // First term in block: assertEquals(1, docFreq(r, "aa0")); // Scan forward to another term in same block assertEquals(1, docFreq(r, "aa2")); assertEquals(1, docFreq(r, "aa")); // Reset same block then scan forwards assertEquals(1, docFreq(r, "aa1")); // Not found, in same block assertEquals(0, docFreq(r, "aa5")); // Found, in same block assertEquals(1, docFreq(r, "aa2")); // Not found in index: assertEquals(0, docFreq(r, "b0")); // Found: assertEquals(1, docFreq(r, "aa2")); // Found, rewind: assertEquals(1, docFreq(r, "aa0")); // First term in block: assertEquals(1, docFreq(r, "bb0")); // Scan forward to another term in same block assertEquals(1, docFreq(r, "bb2")); // Reset same block then scan forwards assertEquals(1, docFreq(r, "bb1")); // Not found, in same block assertEquals(0, docFreq(r, "bb5")); // Found, in same block assertEquals(1, docFreq(r, "bb2")); // Not found in index: assertEquals(0, docFreq(r, "b0")); // Found: assertEquals(1, docFreq(r, "bb2")); // Found, rewind: assertEquals(1, docFreq(r, "bb0")); close(); } // tests: // - test same prefix has non-floor block and floor block (ie, has 2 long outputs on same term // prefix) // - term that's entirely in the index public void testFloorBlocks() throws Exception { final String[] terms = new String[] { "aa0", "aa1", "aa2", "aa3", "aa4", "aa5", "aa6", "aa7", "aa8", "aa9", "aa", "xx" }; r = makeIndex(terms); // r = makeIndex("aa0", "aa1", "aa2", "aa3", "aa4", "aa5", "aa6", "aa7", "aa8", "aa9"); // First term in first block: assertEquals(1, docFreq(r, "aa0")); assertEquals(1, docFreq(r, "aa4")); // No block assertEquals(0, docFreq(r, "bb0")); // Second block assertEquals(1, docFreq(r, "aa4")); // Backwards to prior floor block: assertEquals(1, docFreq(r, "aa0")); // Forwards to last floor block: assertEquals(1, docFreq(r, "aa9")); assertEquals(0, docFreq(r, "a")); assertEquals(1, docFreq(r, "aa")); assertEquals(0, docFreq(r, "a")); assertEquals(1, docFreq(r, "aa")); // Forwards to last floor block: assertEquals(1, docFreq(r, "xx")); assertEquals(1, docFreq(r, "aa1")); assertEquals(0, docFreq(r, "yy")); assertEquals(1, docFreq(r, "xx")); assertEquals(1, docFreq(r, "aa9")); assertEquals(1, docFreq(r, "xx")); assertEquals(1, docFreq(r, "aa4")); final TermsEnum te = MultiTerms.getTerms(r, FIELD).iterator(); while (te.next() != null) { // System.out.println("TEST: next term=" + te.term().utf8ToString()); } assertTrue(seekExact(te, "aa1")); assertEquals("aa2", next(te)); assertTrue(seekExact(te, "aa8")); assertEquals("aa9", next(te)); assertEquals("xx", next(te)); testRandomSeeks(r, terms); close(); } public void testZeroTerms() throws Exception { d = newDirectory(); final RandomIndexWriter w = new RandomIndexWriter(random(), d); Document doc = new Document(); doc.add(newTextField("field", "one two three", Field.Store.NO)); doc = new Document(); doc.add(newTextField("field2", "one two three", Field.Store.NO)); w.addDocument(doc); w.commit(); w.deleteDocuments(new Term("field", "one")); w.forceMerge(1); IndexReader r = w.getReader(); w.close(); assertEquals(1, r.numDocs()); assertEquals(1, r.maxDoc()); Terms terms = MultiTerms.getTerms(r, "field"); if (terms != null) { assertNull(terms.iterator().next()); } r.close(); d.close(); } private String getRandomString() { // return _TestUtil.randomSimpleString(random()); return TestUtil.randomRealisticUnicodeString(random()); } public void testRandomTerms() throws Exception { final String[] terms = new String[TestUtil.nextInt(random(), 1, atLeast(1000))]; final Set<String> seen = new HashSet<>(); final boolean allowEmptyString = random().nextBoolean(); if (random().nextInt(10) == 7 && terms.length > 2) { // Sometimes add a bunch of terms sharing a longish common prefix: final int numTermsSamePrefix = random().nextInt(terms.length / 2); if (numTermsSamePrefix > 0) { String prefix; while (true) { prefix = getRandomString(); if (prefix.length() < 5) { continue; } else { break; } } while (seen.size() < numTermsSamePrefix) { final String t = prefix + getRandomString(); if (!seen.contains(t)) { terms[seen.size()] = t; seen.add(t); } } } } while (seen.size() < terms.length) { final String t = getRandomString(); if (!seen.contains(t) && (allowEmptyString || t.length() != 0)) { terms[seen.size()] = t; seen.add(t); } } r = makeIndex(terms); testRandomSeeks(r, terms); close(); } // sugar private boolean seekExact(TermsEnum te, String term) throws IOException { return te.seekExact(newBytesRef(term)); } // sugar private String next(TermsEnum te) throws IOException { final BytesRef br = te.next(); if (br == null) { return null; } else { return br.utf8ToString(); } } private BytesRef getNonExistTerm(BytesRef[] terms) { BytesRef t = null; while (true) { final String ts = getRandomString(); t = newBytesRef(ts); if (Arrays.binarySearch(terms, t) < 0) { return t; } } } private record TermAndState(BytesRef term, TermState state) {} private void testRandomSeeks(IndexReader r, String... validTermStrings) throws IOException { final BytesRef[] validTerms = new BytesRef[validTermStrings.length]; for (int termIDX = 0; termIDX < validTermStrings.length; termIDX++) { validTerms[termIDX] = newBytesRef(validTermStrings[termIDX]); } Arrays.sort(validTerms); if (VERBOSE) { System.out.println("TEST: " + validTerms.length + " terms:"); for (BytesRef t : validTerms) { System.out.println(" " + t.utf8ToString() + " " + t); } } final TermsEnum te = MultiTerms.getTerms(r, FIELD).iterator(); final int END_LOC = -validTerms.length - 1; final List<TermAndState> termStates = new ArrayList<>(); for (int iter = 0; iter < 100 * RANDOM_MULTIPLIER; iter++) { final BytesRef t; int loc; final TermState termState; if (random().nextInt(6) == 4) { // pick term that doens't exist: t = getNonExistTerm(validTerms); termState = null; if (VERBOSE) { System.out.println("\nTEST: invalid term=" + t.utf8ToString()); } loc = Arrays.binarySearch(validTerms, t); } else if (termStates.size() != 0 && random().nextInt(4) == 1) { final TermAndState ts = termStates.get(random().nextInt(termStates.size())); t = ts.term; loc = Arrays.binarySearch(validTerms, t); assertTrue(loc >= 0); termState = ts.state; if (VERBOSE) { System.out.println("\nTEST: valid termState term=" + t.utf8ToString()); } } else { // pick valid term loc = random().nextInt(validTerms.length); t = BytesRef.deepCopyOf(validTerms[loc]); termState = null; if (VERBOSE) { System.out.println("\nTEST: valid term=" + t.utf8ToString()); } } // seekCeil or seekExact: final boolean doSeekExact = random().nextBoolean(); if (termState != null) { if (VERBOSE) { System.out.println(" seekExact termState"); } te.seekExact(t, termState); } else if (doSeekExact) { if (VERBOSE) { System.out.println(" seekExact"); } assertEquals(loc >= 0, te.seekExact(t)); } else { if (VERBOSE) { System.out.println(" seekCeil"); } final TermsEnum.SeekStatus result = te.seekCeil(t); if (VERBOSE) { System.out.println(" got " + result); } if (loc >= 0) { assertEquals(TermsEnum.SeekStatus.FOUND, result); } else if (loc == END_LOC) { assertEquals(TermsEnum.SeekStatus.END, result); } else { assert loc >= -validTerms.length; assertEquals(TermsEnum.SeekStatus.NOT_FOUND, result); } } if (loc >= 0) { assertEquals(t, te.term()); } else if (doSeekExact) { // TermsEnum is unpositioned if seekExact returns false continue; } else if (loc == END_LOC) { continue; } else { loc = -loc - 1; assertEquals(validTerms[loc], te.term()); } // Do a bunch of next's after the seek final int numNext = random().nextInt(validTerms.length); for (int nextCount = 0; nextCount < numNext; nextCount++) { if (VERBOSE) { System.out.println("\nTEST: next loc=" + loc + " of " + validTerms.length); } final BytesRef t2 = te.next(); loc++; if (loc == validTerms.length) { assertNull(t2); break; } else { assertEquals(validTerms[loc], t2); if (random().nextInt(40) == 17 && termStates.size() < 100) { termStates.add(new TermAndState(validTerms[loc], te.termState())); } } } } } public void testIntersectBasic() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setMergePolicy(new LogDocMergePolicy()); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); Document doc = new Document(); doc.add(newTextField("field", "aaa", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newTextField("field", "bbb", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newTextField("field", "ccc", Field.Store.NO)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = w.getReader(); w.close(); LeafReader sub = getOnlyLeafReader(r); Terms terms = sub.terms("field"); Automaton automaton = new RegExp(".*", RegExp.NONE).toAutomaton(); CompiledAutomaton ca = new CompiledAutomaton(automaton, false, false); TermsEnum te = terms.intersect(ca, null); assertEquals("aaa", te.next().utf8ToString()); assertEquals(0, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("bbb", te.next().utf8ToString()); assertEquals(1, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("ccc", te.next().utf8ToString()); assertEquals(2, te.postings(null, PostingsEnum.NONE).nextDoc()); assertNull(te.next()); te = terms.intersect(ca, newBytesRef("abc")); assertEquals("bbb", te.next().utf8ToString()); assertEquals(1, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("ccc", te.next().utf8ToString()); assertEquals(2, te.postings(null, PostingsEnum.NONE).nextDoc()); assertNull(te.next()); te = terms.intersect(ca, newBytesRef("aaa")); assertEquals("bbb", te.next().utf8ToString()); assertEquals(1, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("ccc", te.next().utf8ToString()); assertEquals(2, te.postings(null, PostingsEnum.NONE).nextDoc()); assertNull(te.next()); r.close(); dir.close(); } public void testIntersectStartTerm() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setMergePolicy(new LogDocMergePolicy()); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); Document doc = new Document(); doc.add(newStringField("field", "abc", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("field", "abd", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("field", "acd", Field.Store.NO)); w.addDocument(doc); doc = new Document(); doc.add(newStringField("field", "bcd", Field.Store.NO)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = w.getReader(); w.close(); LeafReader sub = getOnlyLeafReader(r); Terms terms = sub.terms("field"); Automaton automaton = new RegExp(".*d", RegExp.NONE).toAutomaton(); automaton = Operations.determinize(automaton, Operations.DEFAULT_DETERMINIZE_WORK_LIMIT); CompiledAutomaton ca = new CompiledAutomaton(automaton, false, false); TermsEnum te; // should seek to startTerm te = terms.intersect(ca, newBytesRef("aad")); assertEquals("abd", te.next().utf8ToString()); assertEquals(1, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("acd", te.next().utf8ToString()); assertEquals(2, te.postings(null, PostingsEnum.NONE).nextDoc()); assertEquals("bcd", te.next().utf8ToString()); assertEquals(3, te.postings(null, PostingsEnum.NONE).nextDoc()); assertNull(te.next()); // should fail to find ceil label on second arc, rewind te = terms.intersect(ca, newBytesRef("add")); assertEquals("bcd", te.next().utf8ToString()); assertEquals(3, te.postings(null, PostingsEnum.NONE).nextDoc()); assertNull(te.next()); // should reach end te = terms.intersect(ca, newBytesRef("bcd")); assertNull(te.next()); te = terms.intersect(ca, newBytesRef("ddd")); assertNull(te.next()); r.close(); dir.close(); } public void testIntersectEmptyString() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setMergePolicy(new LogDocMergePolicy()); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); Document doc = new Document(); doc.add(newStringField("field", "", Field.Store.NO)); doc.add(newStringField("field", "abc", Field.Store.NO)); w.addDocument(doc); doc = new Document(); // add empty string to both documents, so that singletonDocID == -1. // For a FST-based term dict, we'll expect to see the first arc is // flaged with HAS_FINAL_OUTPUT doc.add(newStringField("field", "abc", Field.Store.NO)); doc.add(newStringField("field", "", Field.Store.NO)); w.addDocument(doc); w.forceMerge(1); DirectoryReader r = w.getReader(); w.close(); LeafReader sub = getOnlyLeafReader(r); Terms terms = sub.terms("field"); Automaton automaton = new RegExp(".*", RegExp.NONE).toAutomaton(); // accept ALL CompiledAutomaton ca = new CompiledAutomaton(automaton, false, false); TermsEnum te = terms.intersect(ca, null); PostingsEnum de; assertEquals("", te.next().utf8ToString()); de = te.postings(null, PostingsEnum.NONE); assertEquals(0, de.nextDoc()); assertEquals(1, de.nextDoc()); assertEquals("abc", te.next().utf8ToString()); de = te.postings(null, PostingsEnum.NONE); assertEquals(0, de.nextDoc()); assertEquals(1, de.nextDoc()); assertNull(te.next()); // pass empty string te = terms.intersect(ca, newBytesRef("")); assertEquals("abc", te.next().utf8ToString()); de = te.postings(null, PostingsEnum.NONE); assertEquals(0, de.nextDoc()); assertEquals(1, de.nextDoc()); assertNull(te.next()); r.close(); dir.close(); } // LUCENE-5667 public void testCommonPrefixTerms() throws Exception { Directory d = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), d); Set<String> terms = new HashSet<>(); // String prefix = TestUtil.randomSimpleString(random(), 1, 20); String prefix = TestUtil.randomRealisticUnicodeString(random(), 1, 20); int numTerms = atLeast(100); if (VERBOSE) { System.out.println("TEST: " + numTerms + " terms; prefix=" + prefix); } while (terms.size() < numTerms) { // terms.add(prefix + TestUtil.randomSimpleString(random(), 1, 20)); terms.add(prefix + TestUtil.randomRealisticUnicodeString(random(), 1, 20)); } for (String term : terms) { Document doc = new Document(); doc.add(newStringField("id", term, Field.Store.YES)); w.addDocument(doc); } IndexReader r = w.getReader(); if (VERBOSE) { System.out.println("\nTEST: reader=" + r); } TermsEnum termsEnum = MultiTerms.getTerms(r, "id").iterator(); PostingsEnum postingsEnum = null; PerThreadPKLookup pkLookup = new PerThreadPKLookup(r, "id"); StoredFields storedFields = r.storedFields(); int iters = atLeast(numTerms * 3); List<String> termsList = new ArrayList<>(terms); for (int iter = 0; iter < iters; iter++) { String term; boolean shouldExist; if (random().nextBoolean()) { term = termsList.get(random().nextInt(terms.size())); shouldExist = true; } else { term = prefix + TestUtil.randomSimpleString(random(), 1, 20); shouldExist = terms.contains(term); } if (VERBOSE) { System.out.println("\nTEST: try term=" + term); System.out.println(" shouldExist?=" + shouldExist); } BytesRef termBytesRef = newBytesRef(term); boolean actualResult = termsEnum.seekExact(termBytesRef); assertEquals(shouldExist, actualResult); if (shouldExist) { postingsEnum = termsEnum.postings(postingsEnum, 0); int docID = postingsEnum.nextDoc(); assertTrue(docID != PostingsEnum.NO_MORE_DOCS); assertEquals(docID, pkLookup.lookup(termBytesRef)); Document doc = storedFields.document(docID); assertEquals(term, doc.get("id")); if (random().nextInt(7) == 1) { termsEnum.next(); } } else { assertEquals(-1, pkLookup.lookup(termBytesRef)); } if (random().nextInt(7) == 1) { TermsEnum.SeekStatus status = termsEnum.seekCeil(termBytesRef); if (shouldExist) { assertEquals(TermsEnum.SeekStatus.FOUND, status); } else { assertNotSame(TermsEnum.SeekStatus.FOUND, status); } } } r.close(); w.close(); d.close(); } // Stresses out many-terms-in-root-block case: @Nightly public void testVaryingTermsPerSegment() throws Exception { Directory dir = newDirectory(); Set<BytesRef> terms = new HashSet<>(); int MAX_TERMS = atLeast(1000); while (terms.size() < MAX_TERMS) { terms.add(newBytesRef(TestUtil.randomSimpleString(random(), 1, 40))); } List<BytesRef> termsList = new ArrayList<>(terms); StringBuilder sb = new StringBuilder(); for (int termCount = 0; termCount < MAX_TERMS; termCount++) { if (VERBOSE) { System.out.println( "\nTEST: termCount=" + termCount + " add term=" + termsList.get(termCount).utf8ToString()); } sb.append(' '); sb.append(termsList.get(termCount).utf8ToString()); IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random())); iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc); Document doc = new Document(); doc.add(newTextField("field", sb.toString(), Field.Store.NO)); w.addDocument(doc); IndexReader r = w.getReader(); assertEquals(1, r.leaves().size()); TermsEnum te = r.leaves().get(0).reader().terms("field").iterator(); for (int i = 0; i <= termCount; i++) { assertTrue( "term '" + termsList.get(i).utf8ToString() + "' should exist but doesn't", te.seekExact(termsList.get(i))); } for (int i = termCount + 1; i < termsList.size(); i++) { assertFalse( "term '" + termsList.get(i) + "' shouldn't exist but does", te.seekExact(termsList.get(i))); } r.close(); w.close(); } dir.close(); } // LUCENE-7576 public void testIntersectRegexp() throws Exception { Directory d = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), d); Document doc = new Document(); doc.add(newStringField("field", "foobar", Field.Store.NO)); w.addDocument(doc); IndexReader r = w.getReader(); Terms terms = MultiTerms.getTerms(r, "field"); CompiledAutomaton automaton = new CompiledAutomaton(new RegExp("do_not_match_anything").toAutomaton()); String message = expectThrows( IllegalArgumentException.class, () -> { terms.intersect(automaton, null); }) .getMessage(); assertEquals("please use CompiledAutomaton.getTermsEnum instead", message); r.close(); w.close(); d.close(); } // LUCENE-7576 public void testInvalidAutomatonTermsEnum() throws Exception { expectThrows( IllegalArgumentException.class, () -> { new AutomatonTermsEnum( TermsEnum.EMPTY, new CompiledAutomaton(Automata.makeString("foo"))); }); } }
googleapis/google-cloud-java
35,381
java-run/proto-google-cloud-run-v2/src/main/java/com/google/cloud/run/v2/ListExecutionsResponse.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/run/v2/execution.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.run.v2; /** * * * <pre> * Response message containing a list of Executions. * </pre> * * Protobuf type {@code google.cloud.run.v2.ListExecutionsResponse} */ public final class ListExecutionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.run.v2.ListExecutionsResponse) ListExecutionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListExecutionsResponse.newBuilder() to construct. private ListExecutionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListExecutionsResponse() { executions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListExecutionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.run.v2.ExecutionProto .internal_static_google_cloud_run_v2_ListExecutionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.run.v2.ExecutionProto .internal_static_google_cloud_run_v2_ListExecutionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.run.v2.ListExecutionsResponse.class, com.google.cloud.run.v2.ListExecutionsResponse.Builder.class); } public static final int EXECUTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.run.v2.Execution> executions_; /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.run.v2.Execution> getExecutionsList() { return executions_; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.run.v2.ExecutionOrBuilder> getExecutionsOrBuilderList() { return executions_; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ @java.lang.Override public int getExecutionsCount() { return executions_.size(); } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ @java.lang.Override public com.google.cloud.run.v2.Execution getExecutions(int index) { return executions_.get(index); } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ @java.lang.Override public com.google.cloud.run.v2.ExecutionOrBuilder getExecutionsOrBuilder(int index) { return executions_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 < executions_.size(); i++) { output.writeMessage(1, executions_.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 < executions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, executions_.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.run.v2.ListExecutionsResponse)) { return super.equals(obj); } com.google.cloud.run.v2.ListExecutionsResponse other = (com.google.cloud.run.v2.ListExecutionsResponse) obj; if (!getExecutionsList().equals(other.getExecutionsList())) 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 (getExecutionsCount() > 0) { hash = (37 * hash) + EXECUTIONS_FIELD_NUMBER; hash = (53 * hash) + getExecutionsList().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.run.v2.ListExecutionsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.ListExecutionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.run.v2.ListExecutionsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse 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 containing a list of Executions. * </pre> * * Protobuf type {@code google.cloud.run.v2.ListExecutionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.run.v2.ListExecutionsResponse) com.google.cloud.run.v2.ListExecutionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.run.v2.ExecutionProto .internal_static_google_cloud_run_v2_ListExecutionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.run.v2.ExecutionProto .internal_static_google_cloud_run_v2_ListExecutionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.run.v2.ListExecutionsResponse.class, com.google.cloud.run.v2.ListExecutionsResponse.Builder.class); } // Construct using com.google.cloud.run.v2.ListExecutionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (executionsBuilder_ == null) { executions_ = java.util.Collections.emptyList(); } else { executions_ = null; executionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.run.v2.ExecutionProto .internal_static_google_cloud_run_v2_ListExecutionsResponse_descriptor; } @java.lang.Override public com.google.cloud.run.v2.ListExecutionsResponse getDefaultInstanceForType() { return com.google.cloud.run.v2.ListExecutionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.run.v2.ListExecutionsResponse build() { com.google.cloud.run.v2.ListExecutionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.run.v2.ListExecutionsResponse buildPartial() { com.google.cloud.run.v2.ListExecutionsResponse result = new com.google.cloud.run.v2.ListExecutionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.cloud.run.v2.ListExecutionsResponse result) { if (executionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { executions_ = java.util.Collections.unmodifiableList(executions_); bitField0_ = (bitField0_ & ~0x00000001); } result.executions_ = executions_; } else { result.executions_ = executionsBuilder_.build(); } } private void buildPartial0(com.google.cloud.run.v2.ListExecutionsResponse 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.run.v2.ListExecutionsResponse) { return mergeFrom((com.google.cloud.run.v2.ListExecutionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.run.v2.ListExecutionsResponse other) { if (other == com.google.cloud.run.v2.ListExecutionsResponse.getDefaultInstance()) return this; if (executionsBuilder_ == null) { if (!other.executions_.isEmpty()) { if (executions_.isEmpty()) { executions_ = other.executions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureExecutionsIsMutable(); executions_.addAll(other.executions_); } onChanged(); } } else { if (!other.executions_.isEmpty()) { if (executionsBuilder_.isEmpty()) { executionsBuilder_.dispose(); executionsBuilder_ = null; executions_ = other.executions_; bitField0_ = (bitField0_ & ~0x00000001); executionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getExecutionsFieldBuilder() : null; } else { executionsBuilder_.addAllMessages(other.executions_); } } } 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.run.v2.Execution m = input.readMessage( com.google.cloud.run.v2.Execution.parser(), extensionRegistry); if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); executions_.add(m); } else { executionsBuilder_.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.run.v2.Execution> executions_ = java.util.Collections.emptyList(); private void ensureExecutionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { executions_ = new java.util.ArrayList<com.google.cloud.run.v2.Execution>(executions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.run.v2.Execution, com.google.cloud.run.v2.Execution.Builder, com.google.cloud.run.v2.ExecutionOrBuilder> executionsBuilder_; /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public java.util.List<com.google.cloud.run.v2.Execution> getExecutionsList() { if (executionsBuilder_ == null) { return java.util.Collections.unmodifiableList(executions_); } else { return executionsBuilder_.getMessageList(); } } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public int getExecutionsCount() { if (executionsBuilder_ == null) { return executions_.size(); } else { return executionsBuilder_.getCount(); } } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public com.google.cloud.run.v2.Execution getExecutions(int index) { if (executionsBuilder_ == null) { return executions_.get(index); } else { return executionsBuilder_.getMessage(index); } } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder setExecutions(int index, com.google.cloud.run.v2.Execution value) { if (executionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionsIsMutable(); executions_.set(index, value); onChanged(); } else { executionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder setExecutions( int index, com.google.cloud.run.v2.Execution.Builder builderForValue) { if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); executions_.set(index, builderForValue.build()); onChanged(); } else { executionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder addExecutions(com.google.cloud.run.v2.Execution value) { if (executionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionsIsMutable(); executions_.add(value); onChanged(); } else { executionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder addExecutions(int index, com.google.cloud.run.v2.Execution value) { if (executionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionsIsMutable(); executions_.add(index, value); onChanged(); } else { executionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder addExecutions(com.google.cloud.run.v2.Execution.Builder builderForValue) { if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); executions_.add(builderForValue.build()); onChanged(); } else { executionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder addExecutions( int index, com.google.cloud.run.v2.Execution.Builder builderForValue) { if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); executions_.add(index, builderForValue.build()); onChanged(); } else { executionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder addAllExecutions( java.lang.Iterable<? extends com.google.cloud.run.v2.Execution> values) { if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, executions_); onChanged(); } else { executionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder clearExecutions() { if (executionsBuilder_ == null) { executions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { executionsBuilder_.clear(); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public Builder removeExecutions(int index) { if (executionsBuilder_ == null) { ensureExecutionsIsMutable(); executions_.remove(index); onChanged(); } else { executionsBuilder_.remove(index); } return this; } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public com.google.cloud.run.v2.Execution.Builder getExecutionsBuilder(int index) { return getExecutionsFieldBuilder().getBuilder(index); } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public com.google.cloud.run.v2.ExecutionOrBuilder getExecutionsOrBuilder(int index) { if (executionsBuilder_ == null) { return executions_.get(index); } else { return executionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public java.util.List<? extends com.google.cloud.run.v2.ExecutionOrBuilder> getExecutionsOrBuilderList() { if (executionsBuilder_ != null) { return executionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(executions_); } } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public com.google.cloud.run.v2.Execution.Builder addExecutionsBuilder() { return getExecutionsFieldBuilder() .addBuilder(com.google.cloud.run.v2.Execution.getDefaultInstance()); } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public com.google.cloud.run.v2.Execution.Builder addExecutionsBuilder(int index) { return getExecutionsFieldBuilder() .addBuilder(index, com.google.cloud.run.v2.Execution.getDefaultInstance()); } /** * * * <pre> * The resulting list of Executions. * </pre> * * <code>repeated .google.cloud.run.v2.Execution executions = 1;</code> */ public java.util.List<com.google.cloud.run.v2.Execution.Builder> getExecutionsBuilderList() { return getExecutionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.run.v2.Execution, com.google.cloud.run.v2.Execution.Builder, com.google.cloud.run.v2.ExecutionOrBuilder> getExecutionsFieldBuilder() { if (executionsBuilder_ == null) { executionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.run.v2.Execution, com.google.cloud.run.v2.Execution.Builder, com.google.cloud.run.v2.ExecutionOrBuilder>( executions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); executions_ = null; } return executionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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 indicating there are more items than page_size. Use it in the next * ListExecutions request to continue. * </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.run.v2.ListExecutionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.run.v2.ListExecutionsResponse) private static final com.google.cloud.run.v2.ListExecutionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.run.v2.ListExecutionsResponse(); } public static com.google.cloud.run.v2.ListExecutionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListExecutionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListExecutionsResponse>() { @java.lang.Override public ListExecutionsResponse 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<ListExecutionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListExecutionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.run.v2.ListExecutionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graalpython
35,782
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextDictBuiltins.java
/* * Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.graal.python.builtins.modules.cext; import static com.oracle.graal.python.builtins.PythonBuiltinClassType.AttributeError; import static com.oracle.graal.python.builtins.PythonBuiltinClassType.SystemError; import static com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiCallPath.Direct; import static com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiCallPath.Ignored; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.Int; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PY_HASH_T_PTR; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PY_SSIZE_T_PTR; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PyObject; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PyObjectBorrowed; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PyObjectPtr; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.PyObjectTransfer; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.Py_hash_t; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.Py_ssize_t; import static com.oracle.graal.python.builtins.objects.cext.capi.transitions.ArgDescriptor.Void; import static com.oracle.graal.python.nodes.ErrorMessages.BAD_ARG_TO_INTERNAL_FUNC_WAS_S_P; import static com.oracle.graal.python.nodes.ErrorMessages.HASH_MISMATCH; import static com.oracle.graal.python.nodes.ErrorMessages.OBJ_P_HAS_NO_ATTR_S; import static com.oracle.graal.python.nodes.SpecialMethodNames.T_KEYS; import static com.oracle.graal.python.nodes.SpecialMethodNames.T_UPDATE; import java.util.logging.Level; import com.oracle.graal.python.PythonLanguage; import com.oracle.graal.python.builtins.PythonBuiltinClassType; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApi5BuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiBinaryBuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiBuiltin; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiNullaryBuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiQuaternaryBuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiTernaryBuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiUnaryBuiltinNode; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.PromoteBorrowedValue; import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions; import com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess; import com.oracle.graal.python.builtins.objects.common.DynamicObjectStorage; import com.oracle.graal.python.builtins.objects.common.EconomicMapStorage; import com.oracle.graal.python.builtins.objects.common.HashingCollectionNodes.SetItemNode; import com.oracle.graal.python.builtins.objects.common.HashingStorage; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageCopy; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageForEachCallback; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageGetItem; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageGetItemWithHash; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageGetIterator; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageIterator; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageIteratorKey; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageIteratorKeyHash; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageIteratorNext; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageIteratorValue; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageLen; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageSetItem; import com.oracle.graal.python.builtins.objects.common.HashingStorageNodes.HashingStorageSetItemWithHash; import com.oracle.graal.python.builtins.objects.common.KeywordsStorage; import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes.GetItemNode; import com.oracle.graal.python.builtins.objects.dict.DictBuiltins.ClearNode; import com.oracle.graal.python.builtins.objects.dict.DictBuiltins.PopNode; import com.oracle.graal.python.builtins.objects.dict.DictNodes; import com.oracle.graal.python.builtins.objects.dict.PDict; import com.oracle.graal.python.builtins.objects.ints.PInt; import com.oracle.graal.python.builtins.objects.list.PList; import com.oracle.graal.python.builtins.objects.str.StringBuiltins; import com.oracle.graal.python.lib.PyDictDelItem; import com.oracle.graal.python.lib.PyDictSetDefault; import com.oracle.graal.python.lib.PyObjectGetAttr; import com.oracle.graal.python.lib.PyObjectHashNode; import com.oracle.graal.python.lib.PyUnicodeCheckNode; import com.oracle.graal.python.nodes.PRaiseNode; import com.oracle.graal.python.nodes.builtins.ListNodes.ConstructListNode; import com.oracle.graal.python.nodes.call.CallNode; import com.oracle.graal.python.nodes.util.CastToJavaLongExactNode; import com.oracle.graal.python.runtime.exception.PException; import com.oracle.graal.python.runtime.object.PFactory; import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage; import com.oracle.graal.python.util.PythonUtils; import com.oracle.truffle.api.dsl.Bind; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Cached.Exclusive; import com.oracle.truffle.api.dsl.Cached.Shared; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.GenerateCached; import com.oracle.truffle.api.dsl.GenerateInline; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.Frame; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.profiles.InlinedBranchProfile; import com.oracle.truffle.api.profiles.InlinedConditionProfile; import com.oracle.truffle.api.profiles.InlinedLoopConditionProfile; public final class PythonCextDictBuiltins { @CApiBuiltin(ret = PyObjectTransfer, args = {}, call = Direct) abstract static class PyDict_New extends CApiNullaryBuiltinNode { @Specialization static Object run( @Bind PythonLanguage language) { return PFactory.createDict(language); } } @CApiBuiltin(ret = Int, args = {PyObject, PY_SSIZE_T_PTR, PyObjectPtr, PyObjectPtr, PY_HASH_T_PTR}, call = Direct) abstract static class _PyDict_Next extends CApi5BuiltinNode { @Specialization static int next(PDict dict, Object posPtr, Object keyPtr, Object valuePtr, Object hashPtr, @Bind Node inliningTarget, @CachedLibrary(limit = "2") InteropLibrary lib, @Cached CStructAccess.ReadI64Node readI64Node, @Cached CStructAccess.WriteLongNode writeLongNode, @Cached CStructAccess.WritePointerNode writePointerNode, @Cached CApiTransitions.PythonToNativeNode toNativeNode, @Cached InlinedBranchProfile needsRewriteProfile, @Cached InlinedBranchProfile economicMapProfile, @Cached HashingStorageLen lenNode, @Cached HashingStorageGetIterator getIterator, @Cached HashingStorageIteratorNext itNext, @Cached HashingStorageIteratorKey itKey, @Cached HashingStorageIteratorValue itValue, @Cached HashingStorageIteratorKeyHash itKeyHash, @Cached PromoteBorrowedValue promoteKeyNode, @Cached PromoteBorrowedValue promoteValueNode, @Cached HashingStorageSetItem setItem) { /* * We need to promote primitive values and strings to object types for borrowing to work * correctly. This is very hard to do mid-iteration, so we do all the promotion for the * whole dict at once in the first call (which is required to start with position 0). In * order to not violate the ordering, we construct a completely new storage. */ long pos = readI64Node.read(posPtr); if (pos == 0) { HashingStorage storage = dict.getDictStorage(); int len = lenNode.execute(inliningTarget, storage); if (len > 0) { boolean needsRewrite = false; if (storage instanceof EconomicMapStorage) { economicMapProfile.enter(inliningTarget); HashingStorageIterator it = getIterator.execute(inliningTarget, storage); while (itNext.execute(inliningTarget, storage, it)) { if (promoteKeyNode.execute(inliningTarget, itKey.execute(inliningTarget, storage, it)) != null || promoteValueNode.execute(inliningTarget, itValue.execute(inliningTarget, storage, it)) != null) { needsRewrite = true; break; } } } else { /* * Other storages always have string keys or have complex iterators, just * convert them to economic map */ needsRewrite = true; } if (needsRewrite) { needsRewriteProfile.enter(inliningTarget); EconomicMapStorage newStorage = EconomicMapStorage.create(len); HashingStorageIterator it = getIterator.execute(inliningTarget, storage); while (itNext.execute(inliningTarget, storage, it)) { Object key = itKey.execute(inliningTarget, storage, it); Object value = itValue.execute(inliningTarget, storage, it); Object promotedKey = promoteKeyNode.execute(inliningTarget, key); if (promotedKey != null) { key = promotedKey; } Object promotedValue = promoteValueNode.execute(inliningTarget, value); if (promotedValue != null) { value = promotedValue; } // promoted key will never have side-effecting __hash__/__eq__ setItem.execute(null, inliningTarget, newStorage, key, value); } dict.setDictStorage(newStorage); } } } HashingStorage storage = dict.getDictStorage(); HashingStorageIterator it = getIterator.execute(inliningTarget, storage); /* * The iterator index starts from -1, but pos starts from 0, so we subtract 1 here and * add it back later when computing new pos. */ it.setState((int) pos - 1); boolean hasNext = itNext.execute(inliningTarget, storage, it); if (!hasNext) { return 0; } long newPos = it.getState() + 1; writeLongNode.write(posPtr, newPos); if (!lib.isNull(keyPtr)) { Object key = itKey.execute(inliningTarget, storage, it); assert promoteKeyNode.execute(inliningTarget, key) == null; // Borrowed reference writePointerNode.write(keyPtr, toNativeNode.execute(key)); } if (!lib.isNull(valuePtr)) { Object value = itValue.execute(inliningTarget, storage, it); assert promoteValueNode.execute(inliningTarget, value) == null; // Borrowed reference writePointerNode.write(valuePtr, toNativeNode.execute(value)); } if (!lib.isNull(hashPtr)) { long hash = itKeyHash.execute(null, inliningTarget, storage, it); writeLongNode.write(hashPtr, hash); } return 1; } @Fallback @SuppressWarnings("unused") static int run(Object dict, Object posPtr, Object keyPtr, Object valuePtr, Object hashPtr) { return 0; } } @CApiBuiltin(ret = PyObjectTransfer, args = {PyObject, PyObject, PyObject}, call = Direct) abstract static class _PyDict_Pop extends CApiTernaryBuiltinNode { @Specialization static Object pop(PDict dict, Object key, Object defaultValue, @Cached PopNode popNode) { return popNode.execute(null, dict, key, defaultValue); } @Fallback public Object fallback(Object dict, @SuppressWarnings("unused") Object key, @SuppressWarnings("unused") Object defaultValue) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Py_ssize_t, args = {PyObject}, call = Direct) abstract static class PyDict_Size extends CApiUnaryBuiltinNode { @Specialization static int size(PDict dict, @Bind Node inliningTarget, @Cached HashingStorageLen lenNode) { return lenNode.execute(inliningTarget, dict.getDictStorage()); } @Fallback public int fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectTransfer, args = {PyObject}, call = Direct) abstract static class PyDict_Copy extends CApiUnaryBuiltinNode { @Specialization static Object copy(PDict dict, @Bind Node inliningTarget, @Cached HashingStorageCopy copyNode, @Bind PythonLanguage language) { return PFactory.createDict(language, copyNode.execute(inliningTarget, dict.getDictStorage())); } @Fallback Object fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectBorrowed, args = {PyObject, PyObject}, call = Direct) public abstract static class PyDict_GetItem extends CApiBinaryBuiltinNode { @Specialization static Object getItem(PDict dict, Object key, @Bind Node inliningTarget, @Cached HashingStorageGetItem getItem, @Cached PromoteBorrowedValue promoteNode, @Cached SetItemNode setItemNode, @Cached InlinedBranchProfile noResultProfile) { try { Object res = getItem.execute(null, inliningTarget, dict.getDictStorage(), key); if (res == null) { noResultProfile.enter(inliningTarget); return getNativeNull(inliningTarget); } Object promotedValue = promoteNode.execute(inliningTarget, res); if (promotedValue != null) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); return promotedValue; } return res; } catch (PException e) { // PyDict_GetItem suppresses all exceptions for historical reasons return getNativeNull(inliningTarget); } } @Specialization(guards = "!isDict(obj)") static Object getItem(Object obj, @SuppressWarnings("unused") Object key, @Bind Node inliningTarget, @Cached StringBuiltins.StrNewNode strNode) { return PRaiseNode.raiseStatic(inliningTarget, SystemError, BAD_ARG_TO_INTERNAL_FUNC_WAS_S_P, strNode.executeWith(null, obj), obj); } protected boolean isDict(Object obj) { return obj instanceof PDict; } } @CApiBuiltin(ret = PyObjectBorrowed, args = {PyObject, PyObject}, call = Direct) abstract static class PyDict_GetItemWithError extends CApiBinaryBuiltinNode { @Specialization static Object getItem(PDict dict, Object key, @Bind Node inliningTarget, @Cached HashingStorageGetItem getItem, @Cached PromoteBorrowedValue promoteNode, @Cached SetItemNode setItemNode, @Cached InlinedBranchProfile noResultProfile) { Object res = getItem.execute(null, inliningTarget, dict.getDictStorage(), key); if (res == null) { noResultProfile.enter(inliningTarget); return getNativeNull(inliningTarget); } Object promotedValue = promoteNode.execute(inliningTarget, res); if (promotedValue != null) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); return promotedValue; } return res; } @Fallback Object fallback(Object dict, @SuppressWarnings("unused") Object key) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject, PyObject}, call = Direct) abstract static class PyDict_SetItem extends CApiTernaryBuiltinNode { @Specialization static int setItem(PDict dict, Object key, Object value, @Bind Node inliningTarget, @Cached SetItemNode setItemNode) { setItemNode.execute(null, inliningTarget, dict, key, value); return 0; } @SuppressWarnings("unused") @Fallback int fallback(Object dict, Object key, Object value) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject, PyObject, Py_hash_t}, call = Direct) abstract static class _PyDict_SetItem_KnownHash extends CApiQuaternaryBuiltinNode { @Specialization static int setItem(PDict dict, Object key, Object value, Object givenHash, @Bind Node inliningTarget, @Cached PyObjectHashNode hashNode, @Cached CastToJavaLongExactNode castToLong, @Cached SetItemNode setItemNode, @Cached InlinedBranchProfile wrongHashProfile, @Cached PRaiseNode raiseNode) { if (hashNode.execute(null, inliningTarget, key) != castToLong.execute(inliningTarget, givenHash)) { wrongHashProfile.enter(inliningTarget); throw raiseNode.raise(inliningTarget, PythonBuiltinClassType.AssertionError, HASH_MISMATCH); } setItemNode.execute(null, inliningTarget, dict, key, value); return 0; } @SuppressWarnings("unused") @Fallback int fallback(Object dict, Object key, Object value, Object givenHash) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectBorrowed, args = {PyObject, PyObject, PyObject}, call = Direct) abstract static class PyDict_SetDefault extends CApiTernaryBuiltinNode { @Specialization static Object setItem(PDict dict, Object key, Object value, @Bind Node inliningTarget, @Cached PyDictSetDefault setDefault) { return setDefault.execute(null, inliningTarget, dict, key, value); } @Fallback public Object fallback(Object dict, @SuppressWarnings("unused") Object key, @SuppressWarnings("unused") Object value) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject}, call = Direct) abstract static class PyDict_DelItem extends CApiBinaryBuiltinNode { @Specialization static int delItem(PDict dict, Object key, @Bind Node inliningTarget, @Cached PyDictDelItem delItemNode) { delItemNode.execute(null, inliningTarget, dict, key); return 0; } @Fallback public int fallback(Object dict, @SuppressWarnings("unused") Object key) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject}, call = Direct) abstract static class PyDict_Update extends CApiBinaryBuiltinNode { @Specialization static int update(PDict dict, Object other, @Cached DictNodes.UpdateNode updateNode) { updateNode.execute(null, dict, other); return 0; } @Fallback public int fallback(Object dict, @SuppressWarnings("unused") Object other) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject}, call = Direct) abstract static class PyDict_Contains extends CApiBinaryBuiltinNode { @Specialization static int contains(PDict dict, Object key, @Bind Node inliningTarget, @Cached HashingStorageGetItem getItem) { return PInt.intValue(getItem.hasKey(null, inliningTarget, dict.getDictStorage(), key)); } @Fallback public int fallback(Object dict, @SuppressWarnings("unused") Object key) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Void, args = {PyObject}, call = Direct) abstract static class PyDict_Clear extends CApiUnaryBuiltinNode { @Specialization static Object keys(PDict dict, @Cached ClearNode clearNode) { return clearNode.execute(null, dict); } @Fallback public Object fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectTransfer, args = {PyObject}, call = Direct) abstract static class PyDict_Keys extends CApiUnaryBuiltinNode { @Specialization static Object keys(PDict dict, @Cached ConstructListNode listNode, @Bind PythonLanguage language) { return listNode.execute(null, PFactory.createDictKeysView(language, dict)); } @Fallback Object fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectTransfer, args = {PyObject}, call = Direct) abstract static class PyDict_Values extends CApiUnaryBuiltinNode { @Specialization static Object values(PDict dict, @Cached ConstructListNode listNode, @Bind PythonLanguage language) { return listNode.execute(null, PFactory.createDictValuesView(language, dict)); } @Fallback Object fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = PyObjectTransfer, args = {PyObject}, call = Direct) abstract static class PyDict_Items extends CApiUnaryBuiltinNode { @Specialization static Object items(PDict dict, @Cached ConstructListNode listNode, @Bind PythonLanguage language) { return listNode.execute(null, PFactory.createDictItemsView(language, dict)); } @Fallback Object fallback(Object dict) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject, PyObject, Int}, call = Direct) abstract static class PyDict_Merge extends CApiTernaryBuiltinNode { @Specialization(guards = {"override != 0"}) static int merge(PDict a, Object b, @SuppressWarnings("unused") int override, @Bind Node inliningTarget, @Exclusive @Cached PyObjectGetAttr getKeys, @Exclusive @Cached PyObjectGetAttr getUpdate, @Shared @Cached CallNode callNode, @Cached PRaiseNode raiseNode) { // lookup "keys" to raise the right error: if (getKeys.execute(null, inliningTarget, b, T_KEYS) == PNone.NO_VALUE) { throw raiseNode.raise(inliningTarget, AttributeError, OBJ_P_HAS_NO_ATTR_S, b, T_KEYS); } Object updateCallable = getUpdate.execute(null, inliningTarget, a, T_UPDATE); callNode.executeWithoutFrame(updateCallable, new Object[]{b}); return 0; } @Specialization(guards = "override == 0") static int merge(PDict a, PDict b, @SuppressWarnings("unused") int override, @Bind Node inliningTarget, @Cached HashingStorageGetIterator getBIter, @Cached HashingStorageIteratorNext itBNext, @Cached HashingStorageIteratorKey itBKey, @Cached HashingStorageIteratorValue itBValue, @Cached HashingStorageIteratorKeyHash itBKeyHash, @Cached HashingStorageGetItemWithHash getAItem, @Cached HashingStorageSetItemWithHash setAItem, @Exclusive @Cached InlinedLoopConditionProfile loopProfile) { HashingStorage bStorage = b.getDictStorage(); HashingStorageIterator bIt = getBIter.execute(inliningTarget, bStorage); HashingStorage aStorage = a.getDictStorage(); while (loopProfile.profile(inliningTarget, itBNext.execute(inliningTarget, bStorage, bIt))) { Object key = itBKey.execute(inliningTarget, bStorage, bIt); long hash = itBKeyHash.execute(null, inliningTarget, bStorage, bIt); if (getAItem.execute(null, inliningTarget, aStorage, key, hash) != null) { setAItem.execute(null, inliningTarget, aStorage, key, hash, itBValue.execute(inliningTarget, bStorage, bIt)); } } return 0; } // @Exclusive for truffle-interpreted-performance @Specialization(guards = {"override == 0", "!isDict(b)"}) static int merge(PDict a, Object b, @SuppressWarnings("unused") int override, @Bind Node inliningTarget, @Exclusive @Cached PyObjectGetAttr getKeys, @Shared @Cached CallNode callNode, @Cached ConstructListNode listNode, @Cached GetItemNode getKeyNode, @Cached com.oracle.graal.python.lib.PyObjectGetItem getValueNode, @Cached HashingStorageGetItem getItemA, @Cached HashingStorageSetItem setItemA, @Exclusive @Cached InlinedLoopConditionProfile loopProfile, @Cached InlinedBranchProfile noKeyProfile) { Object attr = getKeys.execute(null, inliningTarget, a, T_KEYS); PList keys = listNode.execute(null, callNode.execute(null, attr)); SequenceStorage keysStorage = keys.getSequenceStorage(); HashingStorage aStorage = a.getDictStorage(); int size = keysStorage.length(); loopProfile.profileCounted(inliningTarget, size); for (int i = 0; loopProfile.inject(inliningTarget, i < size); i++) { Object key = getKeyNode.execute(keysStorage, i); if (!getItemA.hasKey(null, inliningTarget, aStorage, key)) { noKeyProfile.enter(inliningTarget); Object value = getValueNode.execute(null, inliningTarget, b, key); aStorage = setItemA.execute(null, inliningTarget, aStorage, key, value); } } a.setDictStorage(aStorage); return 0; } @Fallback int fallback(Object dict, @SuppressWarnings("unused") Object b, @SuppressWarnings("unused") Object override) { throw raiseFallback(dict, PythonBuiltinClassType.PDict); } } @CApiBuiltin(ret = Int, args = {PyObject}, call = Ignored) abstract static class GraalPyPrivate_Dict_MaybeUntrack extends CApiUnaryBuiltinNode { @Specialization static int doPDict(@SuppressWarnings("unused") PDict self, @Bind Node inliningTarget, @Cached HashingStorageNodes.HashingStorageForEach forEachNode, @Cached DictTraverseCallback traverseCallback) { HashingStorage dictStorage = self.getDictStorage(); boolean res = forEachNode.execute(null, inliningTarget, dictStorage, traverseCallback, false); if (CApiContext.GC_LOGGER.isLoggable(Level.FINE)) { CApiContext.GC_LOGGER.fine(PythonUtils.formatJString("Maybe untrack dict %s: %s", self, res)); } return PInt.intValue(res); } } @GenerateInline @GenerateCached(false) abstract static class DictTraverseCallback extends HashingStorageForEachCallback<Boolean> { @Override public abstract Boolean execute(Frame frame, Node inliningTarget, HashingStorage storage, HashingStorageIterator it, Boolean s); @Specialization static Boolean doGeneric(@SuppressWarnings("unused") VirtualFrame frame, Node inliningTarget, HashingStorage storage, HashingStorageIterator it, Boolean accumulator, @Cached HashingStorageIteratorKey nextKey, @Cached HashingStorageIteratorValue nextValue) { if (!accumulator) { return false; } Object key = nextKey.execute(inliningTarget, storage, it); if (isTracked(key, null)) { return false; } Object value = nextValue.execute(inliningTarget, storage, it); if (isTracked(value, null)) { return false; } return true; } /* * #define _PyObject_GC_MAY_BE_TRACKED(obj) \ (PyObject_IS_GC(obj) && \ * (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) */ static boolean isTracked(Object object, CStructAccess.ReadI64Node readI64Node) { // TODO(fa): implement properly return true; // #define _PyObject_GC_IS_TRACKED(o) (_PyGCHead_UNTAG(_Py_AS_GC(o))->_gc_next != 0) // long gcNext = readI64Node.read(gcUntagged, CFields.PyGC_Head___gc_prev); // if (_PyObject_GC_IS_TRACKED(op)) // if (gcNext != 0) { // return true; // } // return false; } } @CApiBuiltin(ret = Int, args = {PyObject}, call = Direct) abstract static class _PyDict_HasOnlyStringKeys extends CApiUnaryBuiltinNode { @Specialization static int check(PDict dict, @Bind Node inliningTarget, @Cached InlinedConditionProfile storageProfile, @Cached InlinedLoopConditionProfile loopConditionProfile, @Cached HashingStorageGetIterator getIter, @Cached HashingStorageIteratorNext getIterNext, @Cached HashingStorageIteratorKey getIterKey, @Cached PyUnicodeCheckNode check) { HashingStorage storage = dict.getDictStorage(); // Keywords and dynamic object storages only allow strings if (storageProfile.profile(inliningTarget, storage instanceof KeywordsStorage || storage instanceof DynamicObjectStorage)) { return 1; } HashingStorageIterator it = getIter.execute(inliningTarget, storage); while (loopConditionProfile.profile(inliningTarget, getIterNext.execute(inliningTarget, storage, it))) { Object key = getIterKey.execute(inliningTarget, storage, it); if (!check.execute(inliningTarget, key)) { return 0; } } return 1; } } }
googleapis/google-cloud-java
35,348
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetServiceAttachmentRequest.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 ServiceAttachments.Get. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetServiceAttachmentRequest} */ public final class GetServiceAttachmentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetServiceAttachmentRequest) GetServiceAttachmentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GetServiceAttachmentRequest.newBuilder() to construct. private GetServiceAttachmentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GetServiceAttachmentRequest() { project_ = ""; region_ = ""; serviceAttachment_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GetServiceAttachmentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetServiceAttachmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetServiceAttachmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetServiceAttachmentRequest.class, com.google.cloud.compute.v1.GetServiceAttachmentRequest.Builder.class); } private int bitField0_; public static final int PROJECT_FIELD_NUMBER = 227560217; @SuppressWarnings("serial") private volatile java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REGION_FIELD_NUMBER = 138946292; @SuppressWarnings("serial") private volatile java.lang.Object region_ = ""; /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ @java.lang.Override public java.lang.String getRegion() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } } /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ @java.lang.Override public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_ATTACHMENT_FIELD_NUMBER = 338957549; @SuppressWarnings("serial") private volatile java.lang.Object serviceAttachment_ = ""; /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The serviceAttachment. */ @java.lang.Override public java.lang.String getServiceAttachment() { java.lang.Object ref = serviceAttachment_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceAttachment_ = s; return s; } } /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for serviceAttachment. */ @java.lang.Override public com.google.protobuf.ByteString getServiceAttachmentBytes() { java.lang.Object ref = serviceAttachment_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceAttachment_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SHOW_NAT_IPS_FIELD_NUMBER = 485502156; private boolean showNatIps_ = false; /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @return Whether the showNatIps field is set. */ @java.lang.Override public boolean hasShowNatIps() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @return The showNatIps. */ @java.lang.Override public boolean getShowNatIps() { return showNatIps_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceAttachment_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 338957549, serviceAttachment_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeBool(485502156, showNatIps_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceAttachment_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(338957549, serviceAttachment_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(485502156, showNatIps_); } 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.GetServiceAttachmentRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GetServiceAttachmentRequest other = (com.google.cloud.compute.v1.GetServiceAttachmentRequest) obj; if (!getProject().equals(other.getProject())) return false; if (!getRegion().equals(other.getRegion())) return false; if (!getServiceAttachment().equals(other.getServiceAttachment())) return false; if (hasShowNatIps() != other.hasShowNatIps()) return false; if (hasShowNatIps()) { if (getShowNatIps() != other.getShowNatIps()) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); hash = (37 * hash) + REGION_FIELD_NUMBER; hash = (53 * hash) + getRegion().hashCode(); hash = (37 * hash) + SERVICE_ATTACHMENT_FIELD_NUMBER; hash = (53 * hash) + getServiceAttachment().hashCode(); if (hasShowNatIps()) { hash = (37 * hash) + SHOW_NAT_IPS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getShowNatIps()); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest 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.GetServiceAttachmentRequest 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 ServiceAttachments.Get. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.GetServiceAttachmentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetServiceAttachmentRequest) com.google.cloud.compute.v1.GetServiceAttachmentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetServiceAttachmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GetServiceAttachmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GetServiceAttachmentRequest.class, com.google.cloud.compute.v1.GetServiceAttachmentRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.GetServiceAttachmentRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; project_ = ""; region_ = ""; serviceAttachment_ = ""; showNatIps_ = false; 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_GetServiceAttachmentRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GetServiceAttachmentRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GetServiceAttachmentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GetServiceAttachmentRequest build() { com.google.cloud.compute.v1.GetServiceAttachmentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GetServiceAttachmentRequest buildPartial() { com.google.cloud.compute.v1.GetServiceAttachmentRequest result = new com.google.cloud.compute.v1.GetServiceAttachmentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.GetServiceAttachmentRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.project_ = project_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.region_ = region_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.serviceAttachment_ = serviceAttachment_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000008) != 0)) { result.showNatIps_ = showNatIps_; 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.GetServiceAttachmentRequest) { return mergeFrom((com.google.cloud.compute.v1.GetServiceAttachmentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.GetServiceAttachmentRequest other) { if (other == com.google.cloud.compute.v1.GetServiceAttachmentRequest.getDefaultInstance()) return this; if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getRegion().isEmpty()) { region_ = other.region_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getServiceAttachment().isEmpty()) { serviceAttachment_ = other.serviceAttachment_; bitField0_ |= 0x00000004; onChanged(); } if (other.hasShowNatIps()) { setShowNatIps(other.getShowNatIps()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 1111570338: { region_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1111570338 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1820481738 case -1583306902: { serviceAttachment_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case -1583306902 case -410950048: { showNatIps_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case -410950048 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</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_ |= 0x00000001; 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_ & ~0x00000001); 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_ |= 0x00000001; onChanged(); return this; } private java.lang.Object region_ = ""; /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The region. */ public java.lang.String getRegion() { java.lang.Object ref = region_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); region_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for region. */ public com.google.protobuf.ByteString getRegionBytes() { java.lang.Object ref = region_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); region_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The region to set. * @return This builder for chaining. */ public Builder setRegion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } region_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearRegion() { region_ = getDefaultInstance().getRegion(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Name of the region of this request. * </pre> * * <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for region to set. * @return This builder for chaining. */ public Builder setRegionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); region_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object serviceAttachment_ = ""; /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The serviceAttachment. */ public java.lang.String getServiceAttachment() { java.lang.Object ref = serviceAttachment_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceAttachment_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for serviceAttachment. */ public com.google.protobuf.ByteString getServiceAttachmentBytes() { java.lang.Object ref = serviceAttachment_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); serviceAttachment_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The serviceAttachment to set. * @return This builder for chaining. */ public Builder setServiceAttachment(java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceAttachment_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearServiceAttachment() { serviceAttachment_ = getDefaultInstance().getServiceAttachment(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Name of the ServiceAttachment resource to return. * </pre> * * <code>string service_attachment = 338957549 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for serviceAttachment to set. * @return This builder for chaining. */ public Builder setServiceAttachmentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceAttachment_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private boolean showNatIps_; /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @return Whether the showNatIps field is set. */ @java.lang.Override public boolean hasShowNatIps() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @return The showNatIps. */ @java.lang.Override public boolean getShowNatIps() { return showNatIps_; } /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @param value The showNatIps to set. * @return This builder for chaining. */ public Builder setShowNatIps(boolean value) { showNatIps_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Indicates whether NAT IPs should be included in the response. * </pre> * * <code>optional bool show_nat_ips = 485502156;</code> * * @return This builder for chaining. */ public Builder clearShowNatIps() { bitField0_ = (bitField0_ & ~0x00000008); showNatIps_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.GetServiceAttachmentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetServiceAttachmentRequest) private static final com.google.cloud.compute.v1.GetServiceAttachmentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetServiceAttachmentRequest(); } public static com.google.cloud.compute.v1.GetServiceAttachmentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GetServiceAttachmentRequest> PARSER = new com.google.protobuf.AbstractParser<GetServiceAttachmentRequest>() { @java.lang.Override public GetServiceAttachmentRequest 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<GetServiceAttachmentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GetServiceAttachmentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GetServiceAttachmentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
34,303
java-vision/proto-google-cloud-vision-v1p1beta1/src/main/java/com/google/cloud/vision/v1p1beta1/ImageAnnotatorProto.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/v1p1beta1/image_annotator.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.vision.v1p1beta1; public final class ImageAnnotatorProto { private ImageAnnotatorProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_Feature_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_Feature_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_ImageSource_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_ImageSource_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_Image_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_Image_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_Landmark_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_Landmark_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_LocationInfo_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_LocationInfo_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_Property_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_Property_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_EntityAnnotation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_EntityAnnotation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_SafeSearchAnnotation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_SafeSearchAnnotation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_LatLongRect_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_LatLongRect_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_ColorInfo_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_ColorInfo_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_DominantColorsAnnotation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_DominantColorsAnnotation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_ImageProperties_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_ImageProperties_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_CropHint_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_CropHint_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_CropHintsAnnotation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_CropHintsAnnotation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_CropHintsParams_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_CropHintsParams_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_WebDetectionParams_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_WebDetectionParams_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_TextDetectionParams_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_TextDetectionParams_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_ImageContext_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_ImageContext_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_AnnotateImageRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_AnnotateImageRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_AnnotateImageResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_AnnotateImageResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n" + "3google/cloud/vision/v1p1beta1/image_annotator.proto\022\035google.cloud.vision.v1p1b" + "eta1\032\034google/api/annotations.proto\032\027goog" + "le/api/client.proto\032\037google/api/field_be" + "havior.proto\032,google/cloud/vision/v1p1beta1/geometry.proto\0323google/cloud/vision/" + "v1p1beta1/text_annotation.proto\0321google/cloud/vision/v1p1beta1/web_detection.pro" + "to\032\027google/rpc/status.proto\032\027google/type" + "/color.proto\032\030google/type/latlng.proto\"\341\002\n" + "\007Feature\0229\n" + "\004type\030\001 \001(\0162+.google.cloud.vision.v1p1beta1.Feature.Type\022\023\n" + "\013max_results\030\002 \001(\005\022\r\n" + "\005model\030\003 \001(\t\"\366\001\n" + "\004Type\022\024\n" + "\020TYPE_UNSPECIFIED\020\000\022\022\n" + "\016FACE_DETECTION\020\001\022\026\n" + "\022LANDMARK_DETECTION\020\002\022\022\n" + "\016LOGO_DETECTION\020\003\022\023\n" + "\017LABEL_DETECTION\020\004\022\022\n" + "\016TEXT_DETECTION\020\005\022\033\n" + "\027DOCUMENT_TEXT_DETECTION\020\013\022\031\n" + "\025SAFE_SEARCH_DETECTION\020\006\022\024\n" + "\020IMAGE_PROPERTIES\020\007\022\016\n\n" + "CROP_HINTS\020\t\022\021\n\r" + "WEB_DETECTION\020\n" + "\"7\n" + "\013ImageSource\022\025\n\r" + "gcs_image_uri\030\001 \001(\t\022\021\n" + "\timage_uri\030\002 \001(\t\"T\n" + "\005Image\022\017\n" + "\007content\030\001 \001(\014\022:\n" + "\006source\030\002 \001(\0132*.google.cloud.vision.v1p1beta1.ImageSource\"\233\016\n" + "\016FaceAnnotation\022B\n\r" + "bounding_poly\030\001 \001(\0132+.google.cloud.vision.v1p1beta1.BoundingPoly\022E\n" + "\020fd_bounding_poly\030\002" + " \001(\0132+.google.cloud.vision.v1p1beta1.BoundingPoly\022I\n" + "\tlandmarks\030\003 \003(\01326.goo" + "gle.cloud.vision.v1p1beta1.FaceAnnotation.Landmark\022\022\n\n" + "roll_angle\030\004 \001(\002\022\021\n" + "\tpan_angle\030\005 \001(\002\022\022\n\n" + "tilt_angle\030\006 \001(\002\022\034\n" + "\024detection_confidence\030\007 \001(\002\022\036\n" + "\026landmarking_confidence\030\010 \001(\002\022A\n" + "\016joy_likelihood\030\t \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022D\n" + "\021sorrow_likelihood\030\n" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022C\n" + "\020anger_likelihood\030\013" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022F\n" + "\023surprise_likelihood\030\014" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022K\n" + "\030under_exposed_likelihood\030\r" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022E\n" + "\022blurred_likelihood\030\016" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022F\n" + "\023headwear_likelihood\030\017" + " \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\032\307\007\n" + "\010Landmark\022I\n" + "\004type\030\003" + " \001(\0162;.google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.Type\0229\n" + "\010position\030\004 \001(\0132\'.google.cloud.vision.v1p1beta1.Position\"\264\006\n" + "\004Type\022\024\n" + "\020UNKNOWN_LANDMARK\020\000\022\014\n" + "\010LEFT_EYE\020\001\022\r\n" + "\tRIGHT_EYE\020\002\022\030\n" + "\024LEFT_OF_LEFT_EYEBROW\020\003\022\031\n" + "\025RIGHT_OF_LEFT_EYEBROW\020\004\022\031\n" + "\025LEFT_OF_RIGHT_EYEBROW\020\005\022\032\n" + "\026RIGHT_OF_RIGHT_EYEBROW\020\006\022\031\n" + "\025MIDPOINT_BETWEEN_EYES\020\007\022\014\n" + "\010NOSE_TIP\020\010\022\r\n" + "\tUPPER_LIP\020\t\022\r\n" + "\tLOWER_LIP\020\n" + "\022\016\n\n" + "MOUTH_LEFT\020\013\022\017\n" + "\013MOUTH_RIGHT\020\014\022\020\n" + "\014MOUTH_CENTER\020\r" + "\022\025\n" + "\021NOSE_BOTTOM_RIGHT\020\016\022\024\n" + "\020NOSE_BOTTOM_LEFT\020\017\022\026\n" + "\022NOSE_BOTTOM_CENTER\020\020\022\031\n" + "\025LEFT_EYE_TOP_BOUNDARY\020\021\022\031\n" + "\025LEFT_EYE_RIGHT_CORNER\020\022\022\034\n" + "\030LEFT_EYE_BOTTOM_BOUNDARY\020\023\022\030\n" + "\024LEFT_EYE_LEFT_CORNER\020\024\022\032\n" + "\026RIGHT_EYE_TOP_BOUNDARY\020\025\022\032\n" + "\026RIGHT_EYE_RIGHT_CORNER\020\026\022\035\n" + "\031RIGHT_EYE_BOTTOM_BOUNDARY\020\027\022\031\n" + "\025RIGHT_EYE_LEFT_CORNER\020\030\022\037\n" + "\033LEFT_EYEBROW_UPPER_MIDPOINT\020\031\022 \n" + "\034RIGHT_EYEBROW_UPPER_MIDPOINT\020\032\022\024\n" + "\020LEFT_EAR_TRAGION\020\033\022\025\n" + "\021RIGHT_EAR_TRAGION\020\034\022\022\n" + "\016LEFT_EYE_PUPIL\020\035\022\023\n" + "\017RIGHT_EYE_PUPIL\020\036\022\025\n" + "\021FOREHEAD_GLABELLA\020\037\022\021\n\r" + "CHIN_GNATHION\020 \022\024\n" + "\020CHIN_LEFT_GONION\020!\022\025\n" + "\021CHIN_RIGHT_GONION\020\"\"4\n" + "\014LocationInfo\022$\n" + "\007lat_lng\030\001 \001(\0132\023.google.type.LatLng\"=\n" + "\010Property\022\014\n" + "\004name\030\001 \001(\t\022\r\n" + "\005value\030\002 \001(\t\022\024\n" + "\014uint64_value\030\003 \001(\004\"\274\002\n" + "\020EntityAnnotation\022\013\n" + "\003mid\030\001 \001(\t\022\016\n" + "\006locale\030\002 \001(\t\022\023\n" + "\013description\030\003 \001(\t\022\r\n" + "\005score\030\004 \001(\002\022\022\n\n" + "confidence\030\005 \001(\002\022\022\n\n" + "topicality\030\006 \001(\002\022B\n\r" + "bounding_poly\030\007 \001(\0132+.google.cloud.vision.v1p1beta1.BoundingPoly\022>\n" + "\tlocations\030\010 \003(\0132+.google.cloud.vision.v1p1beta1.LocationInfo\022;\n\n" + "properties\030\t \003(\0132\'.google.cloud.vision.v1p1beta1.Property\"\274\002\n" + "\024SafeSearchAnnotation\0228\n" + "\005adult\030\001 \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\0228\n" + "\005spoof\030\002 \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022:\n" + "\007medical\030\003 \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\022;\n" + "\010violence\030\004 \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\0227\n" + "\004racy\030\t \001(\0162).google.cloud.vision.v1p1beta1.Likelihood\"a\n" + "\013LatLongRect\022(\n" + "\013min_lat_lng\030\001 \001(\0132\023.google.type.LatLng\022(\n" + "\013max_lat_lng\030\002 \001(\0132\023.google.type.LatLng\"U\n" + "\tColorInfo\022!\n" + "\005color\030\001 \001(\0132\022.google.type.Color\022\r\n" + "\005score\030\002 \001(\002\022\026\n" + "\016pixel_fraction\030\003 \001(\002\"T\n" + "\030DominantColorsAnnotation\0228\n" + "\006colors\030\001 \003(\0132(.google.cloud.vision.v1p1beta1.ColorInfo\"c\n" + "\017ImageProperties\022P\n" + "\017dominant_colors\030\001 \001(\01327.google." + "cloud.vision.v1p1beta1.DominantColorsAnnotation\"\177\n" + "\010CropHint\022B\n\r" + "bounding_poly\030\001 \001" + "(\0132+.google.cloud.vision.v1p1beta1.BoundingPoly\022\022\n\n" + "confidence\030\002 \001(\002\022\033\n" + "\023importance_fraction\030\003 \001(\002\"R\n" + "\023CropHintsAnnotation\022;\n\n" + "crop_hints\030\001 \003(\0132\'.google.cloud.vision.v1p1beta1.CropHint\"(\n" + "\017CropHintsParams\022\025\n\r" + "aspect_ratios\030\001 \003(\002\"1\n" + "\022WebDetectionParams\022\033\n" + "\023include_geo_results\030\002 \001(\010\"c\n" + "\023TextDetectionParams\022.\n" + "&enable_text_detection_confidence_score\030\t \001(\010\022\034\n" + "\024advanced_ocr_options\030\013 \003(\t\"\330\002\n" + "\014ImageContext\022A\n\r" + "lat_long_rect\030\001 \001(\0132*.google.cloud.vision.v1p1beta1.LatLongRect\022\026\n" + "\016language_hints\030\002 \003(\t\022I\n" + "\021crop_hints_params\030\004" + " \001(\0132..google.cloud.vision.v1p1beta1.CropHintsParams\022O\n" + "\024web_detection_params\030\006 \001(\01321.google.clo" + "ud.vision.v1p1beta1.WebDetectionParams\022Q\n" + "\025text_detection_params\030\014 \001(\01322.google.c" + "loud.vision.v1p1beta1.TextDetectionParams\"\311\001\n" + "\024AnnotateImageRequest\0223\n" + "\005image\030\001 \001(\0132$.google.cloud.vision.v1p1beta1.Image\0228\n" + "\010features\030\002 \003(\0132&.google.cloud.vision.v1p1beta1.Feature\022B\n\r" + "image_context\030\003 \001(\013" + "2+.google.cloud.vision.v1p1beta1.ImageContext\"\302\006\n" + "\025AnnotateImageResponse\022G\n" + "\020face_annotations\030\001" + " \003(\0132-.google.cloud.vision.v1p1beta1.FaceAnnotation\022M\n" + "\024landmark_annotations\030\002" + " \003(\0132/.google.cloud.vision.v1p1beta1.EntityAnnotation\022I\n" + "\020logo_annotations\030\003" + " \003(\0132/.google.cloud.vision.v1p1beta1.EntityAnnotation\022J\n" + "\021label_annotations\030\004" + " \003(\0132/.google.cloud.vision.v1p1beta1.EntityAnnotation\022I\n" + "\020text_annotations\030\005 \003(\013" + "2/.google.cloud.vision.v1p1beta1.EntityAnnotation\022K\n" + "\024full_text_annotation\030\014 \001(\0132" + "-.google.cloud.vision.v1p1beta1.TextAnnotation\022S\n" + "\026safe_search_annotation\030\006 \001(\01323" + ".google.cloud.vision.v1p1beta1.SafeSearchAnnotation\022S\n" + "\033image_properties_annotation\030\010" + " \001(\0132..google.cloud.vision.v1p1beta1.ImageProperties\022Q\n" + "\025crop_hints_annotation\030\013" + " \001(\01322.google.cloud.vision.v1p1beta1.CropHintsAnnotation\022B\n\r" + "web_detection\030\r" + " \001(\0132+.google.cloud.vision.v1p1beta1.WebDetection\022!\n" + "\005error\030\t \001(\0132\022.google.rpc.Status\"h\n" + "\032BatchAnnotateImagesRequest\022J\n" + "\010requests\030\001" + " \003(\01323.google.cloud.vision.v1p1beta1.AnnotateImageRequestB\003\340A\002\"f\n" + "\033BatchAnnotateImagesResponse\022G\n" + "\tresponses\030\001 \003(\01324" + ".google.cloud.vision.v1p1beta1.AnnotateImageResponse*e\n\n" + "Likelihood\022\013\n" + "\007UNKNOWN\020\000\022\021\n\r" + "VERY_UNLIKELY\020\001\022\014\n" + "\010UNLIKELY\020\002\022\014\n" + "\010POSSIBLE\020\003\022\n\n" + "\006LIKELY\020\004\022\017\n" + "\013VERY_LIKELY\020\0052\311\002\n" + "\016ImageAnnotator\022\276\001\n" + "\023BatchAnnotateImages\0229.google.cloud.vision.v1p1beta1.BatchAnno" + "tateImagesRequest\032:.google.cloud.vision." + "v1p1beta1.BatchAnnotateImagesResponse\"0\332" + "A\010requests\202\323\344\223\002\037\"\032/v1p1beta1/images:anno" + "tate:\001*\032v\312A\025vision.googleapis.com\322A[http" + "s://www.googleapis.com/auth/cloud-platfo" + "rm,https://www.googleapis.com/auth/cloud-visionB{\n" + "!com.google.cloud.vision.v1p1beta1B\023ImageAnnotatorProtoP\001Z<cloud.googl" + "e.com/go/vision/v2/apiv1p1beta1/visionpb;visionpb\370\001\001b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.cloud.vision.v1p1beta1.GeometryProto.getDescriptor(), com.google.cloud.vision.v1p1beta1.TextAnnotationProto.getDescriptor(), com.google.cloud.vision.v1p1beta1.WebDetectionProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), com.google.type.ColorProto.getDescriptor(), com.google.type.LatLngProto.getDescriptor(), }); internal_static_google_cloud_vision_v1p1beta1_Feature_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_vision_v1p1beta1_Feature_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_Feature_descriptor, new java.lang.String[] { "Type", "MaxResults", "Model", }); internal_static_google_cloud_vision_v1p1beta1_ImageSource_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_vision_v1p1beta1_ImageSource_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_ImageSource_descriptor, new java.lang.String[] { "GcsImageUri", "ImageUri", }); internal_static_google_cloud_vision_v1p1beta1_Image_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_vision_v1p1beta1_Image_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_Image_descriptor, new java.lang.String[] { "Content", "Source", }); internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_descriptor, new java.lang.String[] { "BoundingPoly", "FdBoundingPoly", "Landmarks", "RollAngle", "PanAngle", "TiltAngle", "DetectionConfidence", "LandmarkingConfidence", "JoyLikelihood", "SorrowLikelihood", "AngerLikelihood", "SurpriseLikelihood", "UnderExposedLikelihood", "BlurredLikelihood", "HeadwearLikelihood", }); internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_Landmark_descriptor = internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_Landmark_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_FaceAnnotation_Landmark_descriptor, new java.lang.String[] { "Type", "Position", }); internal_static_google_cloud_vision_v1p1beta1_LocationInfo_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_vision_v1p1beta1_LocationInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_LocationInfo_descriptor, new java.lang.String[] { "LatLng", }); internal_static_google_cloud_vision_v1p1beta1_Property_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_vision_v1p1beta1_Property_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_Property_descriptor, new java.lang.String[] { "Name", "Value", "Uint64Value", }); internal_static_google_cloud_vision_v1p1beta1_EntityAnnotation_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_vision_v1p1beta1_EntityAnnotation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_EntityAnnotation_descriptor, new java.lang.String[] { "Mid", "Locale", "Description", "Score", "Confidence", "Topicality", "BoundingPoly", "Locations", "Properties", }); internal_static_google_cloud_vision_v1p1beta1_SafeSearchAnnotation_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_vision_v1p1beta1_SafeSearchAnnotation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_SafeSearchAnnotation_descriptor, new java.lang.String[] { "Adult", "Spoof", "Medical", "Violence", "Racy", }); internal_static_google_cloud_vision_v1p1beta1_LatLongRect_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_vision_v1p1beta1_LatLongRect_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_LatLongRect_descriptor, new java.lang.String[] { "MinLatLng", "MaxLatLng", }); internal_static_google_cloud_vision_v1p1beta1_ColorInfo_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_vision_v1p1beta1_ColorInfo_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_ColorInfo_descriptor, new java.lang.String[] { "Color", "Score", "PixelFraction", }); internal_static_google_cloud_vision_v1p1beta1_DominantColorsAnnotation_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_vision_v1p1beta1_DominantColorsAnnotation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_DominantColorsAnnotation_descriptor, new java.lang.String[] { "Colors", }); internal_static_google_cloud_vision_v1p1beta1_ImageProperties_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_vision_v1p1beta1_ImageProperties_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_ImageProperties_descriptor, new java.lang.String[] { "DominantColors", }); internal_static_google_cloud_vision_v1p1beta1_CropHint_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_vision_v1p1beta1_CropHint_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_CropHint_descriptor, new java.lang.String[] { "BoundingPoly", "Confidence", "ImportanceFraction", }); internal_static_google_cloud_vision_v1p1beta1_CropHintsAnnotation_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_vision_v1p1beta1_CropHintsAnnotation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_CropHintsAnnotation_descriptor, new java.lang.String[] { "CropHints", }); internal_static_google_cloud_vision_v1p1beta1_CropHintsParams_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_cloud_vision_v1p1beta1_CropHintsParams_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_CropHintsParams_descriptor, new java.lang.String[] { "AspectRatios", }); internal_static_google_cloud_vision_v1p1beta1_WebDetectionParams_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_cloud_vision_v1p1beta1_WebDetectionParams_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_WebDetectionParams_descriptor, new java.lang.String[] { "IncludeGeoResults", }); internal_static_google_cloud_vision_v1p1beta1_TextDetectionParams_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_cloud_vision_v1p1beta1_TextDetectionParams_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_TextDetectionParams_descriptor, new java.lang.String[] { "EnableTextDetectionConfidenceScore", "AdvancedOcrOptions", }); internal_static_google_cloud_vision_v1p1beta1_ImageContext_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_cloud_vision_v1p1beta1_ImageContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_ImageContext_descriptor, new java.lang.String[] { "LatLongRect", "LanguageHints", "CropHintsParams", "WebDetectionParams", "TextDetectionParams", }); internal_static_google_cloud_vision_v1p1beta1_AnnotateImageRequest_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_cloud_vision_v1p1beta1_AnnotateImageRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_AnnotateImageRequest_descriptor, new java.lang.String[] { "Image", "Features", "ImageContext", }); internal_static_google_cloud_vision_v1p1beta1_AnnotateImageResponse_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_cloud_vision_v1p1beta1_AnnotateImageResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_AnnotateImageResponse_descriptor, new java.lang.String[] { "FaceAnnotations", "LandmarkAnnotations", "LogoAnnotations", "LabelAnnotations", "TextAnnotations", "FullTextAnnotation", "SafeSearchAnnotation", "ImagePropertiesAnnotation", "CropHintsAnnotation", "WebDetection", "Error", }); internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesRequest_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesRequest_descriptor, new java.lang.String[] { "Requests", }); internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesResponse_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_vision_v1p1beta1_BatchAnnotateImagesResponse_descriptor, new java.lang.String[] { "Responses", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor( descriptor, registry); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.cloud.vision.v1p1beta1.GeometryProto.getDescriptor(); com.google.cloud.vision.v1p1beta1.TextAnnotationProto.getDescriptor(); com.google.cloud.vision.v1p1beta1.WebDetectionProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); com.google.type.ColorProto.getDescriptor(); com.google.type.LatLngProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache/hbase
35,642
hbase-server/src/test/java/org/apache/hadoop/hbase/wal/TestWALFactory.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.hbase.wal; import static org.apache.hadoop.hbase.wal.WALFactory.META_WAL_PROVIDER; import static org.apache.hadoop.hbase.wal.WALFactory.WAL_PROVIDER; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.BindException; import java.util.ArrayList; import java.util.List; import java.util.NavigableMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtil; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionInfoBuilder; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.codec.Codec; import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; import org.apache.hadoop.hbase.coprocessor.SampleRegionWALCoprocessor; import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl; import org.apache.hadoop.hbase.regionserver.wal.CompressionContext; import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener; import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec; import org.apache.hadoop.hbase.regionserver.wal.WALCoprocessorHost; import org.apache.hadoop.hbase.replication.ReplicationStorageFactory; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.CommonFSUtils; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.RecoverLeaseFSUtils; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.wal.WALFactory.Providers; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * WAL tests that can be reused across providers. */ @Category({ RegionServerTests.class, MediumTests.class }) public class TestWALFactory { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestWALFactory.class); private static final Logger LOG = LoggerFactory.getLogger(TestWALFactory.class); protected static Configuration conf; private static MiniDFSCluster cluster; protected final static HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil(); protected static Path hbaseDir; protected static Path hbaseWALDir; protected FileSystem fs; protected Path dir; protected WALFactory wals; private ServerName currentServername; @Rule public final TestName currentTest = new TestName(); @Before public void setUp() throws Exception { fs = cluster.getFileSystem(); dir = new Path(hbaseDir, currentTest.getMethodName()); this.currentServername = ServerName.valueOf(currentTest.getMethodName(), 16010, 1); wals = new WALFactory(conf, this.currentServername.toString()); } @After public void tearDown() throws Exception { // testAppendClose closes the FileSystem, which will prevent us from closing cleanly here. try { wals.close(); } catch (IOException exception) { LOG.warn("Encountered exception while closing wal factory. If you have other errors, this" + " may be the cause. Message: " + exception); LOG.debug("Exception details for failure to close wal factory.", exception); } FileStatus[] entries = fs.listStatus(new Path("/")); for (FileStatus dir : entries) { fs.delete(dir.getPath(), true); } } @BeforeClass public static void setUpBeforeClass() throws Exception { CommonFSUtils.setWALRootDir(TEST_UTIL.getConfiguration(), new Path("file:///tmp/wal")); // Make block sizes small. TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024); // needed for testAppendClose() // quicker heartbeat interval for faster DN death notification TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000); TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1); TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000); // faster failover with cluster.shutdown();fs.close() idiom TEST_UTIL.getConfiguration().setInt("hbase.ipc.client.connect.max.retries", 1); TEST_UTIL.getConfiguration().setInt("dfs.client.block.recovery.retries", 1); TEST_UTIL.getConfiguration().setInt("hbase.ipc.client.connection.maxidletime", 500); TEST_UTIL.getConfiguration().setInt("hbase.lease.recovery.timeout", 10000); TEST_UTIL.getConfiguration().setInt("hbase.lease.recovery.dfs.timeout", 1000); TEST_UTIL.getConfiguration().set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY, SampleRegionWALCoprocessor.class.getName()); TEST_UTIL.startMiniDFSCluster(3); conf = TEST_UTIL.getConfiguration(); cluster = TEST_UTIL.getDFSCluster(); hbaseDir = TEST_UTIL.createRootDir(); hbaseWALDir = TEST_UTIL.createWALRootDir(); } @AfterClass public static void tearDownAfterClass() throws Exception { TEST_UTIL.shutdownMiniCluster(); } @Test public void canCloseSingleton() throws IOException { WALFactory.getInstance(conf).close(); } /** * Just write multiple logs then split. Before fix for HADOOP-2283, this would fail. */ @Test public void testSplit() throws IOException { final TableName tableName = TableName.valueOf(currentTest.getMethodName()); final byte[] rowName = tableName.getName(); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); final int howmany = 3; RegionInfo[] infos = new RegionInfo[3]; Path tableDataDir = CommonFSUtils.getTableDir(hbaseDir, tableName); fs.mkdirs(tableDataDir); Path tabledir = CommonFSUtils.getWALTableDir(conf, tableName); fs.mkdirs(tabledir); for (int i = 0; i < howmany; i++) { infos[i] = RegionInfoBuilder.newBuilder(tableName).setStartKey(Bytes.toBytes("" + i)) .setEndKey(Bytes.toBytes("" + (i + 1))).build(); fs.mkdirs(new Path(tabledir, infos[i].getEncodedName())); fs.mkdirs(new Path(tableDataDir, infos[i].getEncodedName())); LOG.info("allo " + new Path(tabledir, infos[i].getEncodedName()).toString()); } NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); scopes.put(Bytes.toBytes("column"), 0); // Add edits for three regions. for (int ii = 0; ii < howmany; ii++) { for (int i = 0; i < howmany; i++) { final WAL log = wals.getWAL(infos[i]); for (int j = 0; j < howmany; j++) { WALEdit edit = new WALEdit(); byte[] family = Bytes.toBytes("column"); byte[] qualifier = Bytes.toBytes(Integer.toString(j)); byte[] column = Bytes.toBytes("column:" + Integer.toString(j)); edit.add( new KeyValue(rowName, family, qualifier, EnvironmentEdgeManager.currentTime(), column)); LOG.info("Region " + i + ": " + edit); WALKeyImpl walKey = new WALKeyImpl(infos[i].getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes); log.appendData(infos[i], walKey, edit); walKey.getWriteEntry(); } log.sync(); log.rollWriter(true); } } wals.shutdown(); // The below calculation of logDir relies on insider information... WALSplitter should be // connected better // with the WAL system.... not requiring explicit path. The oldLogDir is just made up not used. Path logDir = new Path(new Path(hbaseWALDir, HConstants.HREGION_LOGDIR_NAME), this.currentServername.toString()); Path oldLogDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME); List<Path> splits = WALSplitter.split(hbaseWALDir, logDir, oldLogDir, fs, conf, wals); verifySplits(splits, howmany); } /** * Test new HDFS-265 sync. */ @Test public void Broken_testSync() throws Exception { TableName tableName = TableName.valueOf(currentTest.getMethodName()); MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); // First verify that using streams all works. Path p = new Path(dir, currentTest.getMethodName() + ".fsdos"); FSDataOutputStream out = fs.create(p); out.write(tableName.getName()); Method syncMethod = null; try { syncMethod = out.getClass().getMethod("hflush", new Class<?>[] {}); } catch (NoSuchMethodException e) { try { syncMethod = out.getClass().getMethod("sync", new Class<?>[] {}); } catch (NoSuchMethodException ex) { fail("This version of Hadoop supports neither Syncable.sync() " + "nor Syncable.hflush()."); } } syncMethod.invoke(out, new Object[] {}); FSDataInputStream in = fs.open(p); assertTrue(in.available() > 0); byte[] buffer = new byte[1024]; int read = in.read(buffer); assertEquals(tableName.getName().length, read); out.close(); in.close(); final int total = 20; RegionInfo info = RegionInfoBuilder.newBuilder(tableName).build(); NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); scopes.put(tableName.getName(), 0); final WAL wal = wals.getWAL(info); for (int i = 0; i < total; i++) { WALEdit kvs = new WALEdit(); kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); wal.appendData(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs); } // Now call sync and try reading. Opening a Reader before you sync just // gives you EOFE. wal.sync(); // Open a Reader. Path walPath = AbstractFSWALProvider.getCurrentFileName(wal); int count = NoEOFWALStreamReader.count(wals, fs, walPath); assertEquals(total, count); // Add test that checks to see that an open of a Reader works on a file // that has had a sync done on it. for (int i = 0; i < total; i++) { WALEdit kvs = new WALEdit(); kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); wal.appendData(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs); } wal.sync(); count = NoEOFWALStreamReader.count(wals, fs, walPath); assertTrue(count >= total); // If I sync, should see double the edits. wal.sync(); count = NoEOFWALStreamReader.count(wals, fs, walPath); assertEquals(total * 2, count); // Now do a test that ensures stuff works when we go over block boundary, // especially that we return good length on file. final byte[] value = new byte[1025 * 1024]; // Make a 1M value. for (int i = 0; i < total; i++) { WALEdit kvs = new WALEdit(); kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), value)); wal.appendData(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs); } // Now I should have written out lots of blocks. Sync then read. wal.sync(); count = NoEOFWALStreamReader.count(wals, fs, walPath); assertEquals(total * 3, count); // shutdown and ensure that Reader gets right length also. wal.shutdown(); count = NoEOFWALStreamReader.count(wals, fs, walPath); assertEquals(total * 3, count); } private void verifySplits(final List<Path> splits, final int howmany) throws IOException { assertEquals(howmany * howmany, splits.size()); for (int i = 0; i < splits.size(); i++) { LOG.info("Verifying=" + splits.get(i)); try (WALStreamReader reader = wals.createStreamReader(fs, splits.get(i))) { int count = 0; String previousRegion = null; long seqno = -1; WAL.Entry entry = new WAL.Entry(); while ((entry = reader.next(entry)) != null) { WALKey key = entry.getKey(); String region = Bytes.toString(key.getEncodedRegionName()); // Assert that all edits are for same region. if (previousRegion != null) { assertEquals(previousRegion, region); } LOG.info("oldseqno=" + seqno + ", newseqno=" + key.getSequenceId()); assertTrue(seqno < key.getSequenceId()); seqno = key.getSequenceId(); previousRegion = region; count++; } assertEquals(howmany, count); } } } /* * We pass different values to recoverFileLease() so that different code paths are covered For * this test to pass, requires: 1. HDFS-200 (append support) 2. HDFS-988 (SafeMode should freeze * file operations [FSNamesystem.nextGenerationStampForBlock]) 3. HDFS-142 (on restart, maintain * pendingCreates) */ @Test public void testAppendClose() throws Exception { TableName tableName = TableName.valueOf(currentTest.getMethodName()); RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build(); WAL wal = wals.getWAL(regionInfo); int total = 20; NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); scopes.put(tableName.getName(), 0); MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(); for (int i = 0; i < total; i++) { WALEdit kvs = new WALEdit(); kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs); } // Now call sync to send the data to HDFS datanodes wal.sync(); int namenodePort = cluster.getNameNodePort(); final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal); // Stop the cluster. (ensure restart since we're sharing MiniDFSCluster) try { DistributedFileSystem dfs = cluster.getFileSystem(); dfs.setSafeMode(HdfsConstants.SafeModeAction.SAFEMODE_ENTER); TEST_UTIL.shutdownMiniDFSCluster(); try { // wal.writer.close() will throw an exception, // but still call this since it closes the LogSyncer thread first wal.shutdown(); } catch (IOException e) { LOG.info(e.toString(), e); } fs.close(); // closing FS last so DFSOutputStream can't call close LOG.info("STOPPED first instance of the cluster"); } finally { // Restart the cluster while (cluster.isClusterUp()) { LOG.error("Waiting for cluster to go down"); Thread.sleep(1000); } assertFalse(cluster.isClusterUp()); cluster = null; for (int i = 0; i < 100; i++) { try { cluster = TEST_UTIL.startMiniDFSClusterForTestWAL(namenodePort); break; } catch (BindException e) { LOG.info("Sleeping. BindException bringing up new cluster"); Threads.sleep(1000); } } cluster.waitActive(); fs = cluster.getFileSystem(); LOG.info("STARTED second instance."); } // set the lease period to be 1 second so that the // namenode triggers lease recovery upon append request Method setLeasePeriod = cluster.getClass().getDeclaredMethod("setLeasePeriod", new Class[] { Long.TYPE, Long.TYPE }); setLeasePeriod.setAccessible(true); setLeasePeriod.invoke(cluster, 1000L, 1000L); try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.info(e.toString(), e); } // Now try recovering the log, like the HMaster would do final FileSystem recoveredFs = fs; final Configuration rlConf = conf; class RecoverLogThread extends Thread { public Exception exception = null; @Override public void run() { try { RecoverLeaseFSUtils.recoverFileLease(recoveredFs, walPath, rlConf, null); } catch (IOException e) { exception = e; } } } RecoverLogThread t = new RecoverLogThread(); t.start(); // Timeout after 60 sec. Without correct patches, would be an infinite loop t.join(60 * 1000); if (t.isAlive()) { t.interrupt(); throw new Exception("Timed out waiting for WAL.recoverLog()"); } if (t.exception != null) throw t.exception; // Make sure you can read all the content int count = 0; try (NoEOFWALStreamReader reader = NoEOFWALStreamReader.create(wals, fs, walPath)) { WAL.Entry entry = new WAL.Entry(); while (reader.next(entry) != null) { count++; assertTrue("Should be one KeyValue per WALEdit", entry.getEdit().getCells().size() == 1); } } assertEquals(total, count); // Reset the lease period setLeasePeriod.invoke(cluster, new Object[] { 60000L, 3600000L }); } /** * Tests that we can write out an edit, close, and then read it back in again. */ @Test public void testEditAdd() throws IOException { int colCount = 10; TableDescriptor htd = TableDescriptorBuilder.newBuilder(TableName.valueOf(currentTest.getMethodName())) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("column")).build(); NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); for (byte[] fam : htd.getColumnFamilyNames()) { scopes.put(fam, 0); } byte[] row = Bytes.toBytes("row"); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); // Write columns named 1, 2, 3, etc. and then values of single byte // 1, 2, 3... long timestamp = EnvironmentEdgeManager.currentTime(); WALEdit cols = new WALEdit(); for (int i = 0; i < colCount; i++) { cols.add(new KeyValue(row, Bytes.toBytes("column"), Bytes.toBytes(Integer.toString(i)), timestamp, new byte[] { (byte) (i + '0') })); } RegionInfo info = RegionInfoBuilder.newBuilder(htd.getTableName()).setStartKey(row) .setEndKey(Bytes.toBytes(Bytes.toString(row) + "1")).build(); final WAL log = wals.getWAL(info); final long txid = log.appendData(info, new WALKeyImpl(info.getEncodedNameAsBytes(), htd.getTableName(), EnvironmentEdgeManager.currentTime(), mvcc, scopes), cols); log.sync(txid); log.startCacheFlush(info.getEncodedNameAsBytes(), htd.getColumnFamilyNames()); log.completeCacheFlush(info.getEncodedNameAsBytes(), HConstants.NO_SEQNUM); log.shutdown(); Path filename = AbstractFSWALProvider.getCurrentFileName(log); // Now open a reader on the log and assert append worked. try (NoEOFWALStreamReader reader = NoEOFWALStreamReader.create(wals, fs, filename)) { // Above we added all columns on a single row so we only read one // entry in the below... thats why we have '1'. for (int i = 0; i < 1; i++) { WAL.Entry entry = reader.next(null); if (entry == null) break; WALKey key = entry.getKey(); WALEdit val = entry.getEdit(); assertTrue(Bytes.equals(info.getEncodedNameAsBytes(), key.getEncodedRegionName())); assertTrue(htd.getTableName().equals(key.getTableName())); Cell cell = val.getCells().get(0); assertTrue(Bytes.equals(row, 0, row.length, cell.getRowArray(), cell.getRowOffset(), cell.getRowLength())); assertEquals((byte) (i + '0'), CellUtil.cloneValue(cell)[0]); LOG.info(key + " " + val); } } } @Test public void testAppend() throws IOException { int colCount = 10; TableDescriptor htd = TableDescriptorBuilder.newBuilder(TableName.valueOf(currentTest.getMethodName())) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("column")).build(); NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); for (byte[] fam : htd.getColumnFamilyNames()) { scopes.put(fam, 0); } byte[] row = Bytes.toBytes("row"); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); // Write columns named 1, 2, 3, etc. and then values of single byte // 1, 2, 3... long timestamp = EnvironmentEdgeManager.currentTime(); WALEdit cols = new WALEdit(); for (int i = 0; i < colCount; i++) { cols.add(new KeyValue(row, Bytes.toBytes("column"), Bytes.toBytes(Integer.toString(i)), timestamp, new byte[] { (byte) (i + '0') })); } RegionInfo hri = RegionInfoBuilder.newBuilder(htd.getTableName()).build(); final WAL log = wals.getWAL(hri); final long txid = log.appendData(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), htd.getTableName(), EnvironmentEdgeManager.currentTime(), mvcc, scopes), cols); log.sync(txid); log.startCacheFlush(hri.getEncodedNameAsBytes(), htd.getColumnFamilyNames()); log.completeCacheFlush(hri.getEncodedNameAsBytes(), HConstants.NO_SEQNUM); log.shutdown(); Path filename = AbstractFSWALProvider.getCurrentFileName(log); // Now open a reader on the log and assert append worked. try (WALStreamReader reader = wals.createStreamReader(fs, filename)) { WAL.Entry entry = reader.next(); assertEquals(colCount, entry.getEdit().size()); int idx = 0; for (Cell val : entry.getEdit().getCells()) { assertTrue( Bytes.equals(hri.getEncodedNameAsBytes(), entry.getKey().getEncodedRegionName())); assertTrue(htd.getTableName().equals(entry.getKey().getTableName())); assertTrue(Bytes.equals(row, 0, row.length, val.getRowArray(), val.getRowOffset(), val.getRowLength())); assertEquals((byte) (idx + '0'), CellUtil.cloneValue(val)[0]); System.out.println(entry.getKey() + " " + val); idx++; } } } /** * Test that we can visit entries before they are appended */ @Test public void testVisitors() throws Exception { final int COL_COUNT = 10; final TableName tableName = TableName.valueOf(currentTest.getMethodName()); final byte[] row = Bytes.toBytes("row"); final DumbWALActionsListener visitor = new DumbWALActionsListener(); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); long timestamp = EnvironmentEdgeManager.currentTime(); NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); scopes.put(Bytes.toBytes("column"), 0); RegionInfo hri = RegionInfoBuilder.newBuilder(tableName).build(); final WAL log = wals.getWAL(hri); log.registerWALActionsListener(visitor); for (int i = 0; i < COL_COUNT; i++) { WALEdit cols = new WALEdit(); cols.add(new KeyValue(row, Bytes.toBytes("column"), Bytes.toBytes(Integer.toString(i)), timestamp, new byte[] { (byte) (i + '0') })); log.appendData(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), cols); } log.sync(); assertEquals(COL_COUNT, visitor.increments); log.unregisterWALActionsListener(visitor); WALEdit cols = new WALEdit(); cols.add(new KeyValue(row, Bytes.toBytes("column"), Bytes.toBytes(Integer.toString(11)), timestamp, new byte[] { (byte) (11 + '0') })); log.appendData(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), tableName, EnvironmentEdgeManager.currentTime(), mvcc, scopes), cols); log.sync(); assertEquals(COL_COUNT, visitor.increments); } /** * A loaded WAL coprocessor won't break existing WAL test cases. */ @Test public void testWALCoprocessorLoaded() throws Exception { // test to see whether the coprocessor is loaded or not. WALCoprocessorHost host = wals.getWAL(null).getCoprocessorHost(); Coprocessor c = host.findCoprocessor(SampleRegionWALCoprocessor.class); assertNotNull(c); } static class DumbWALActionsListener implements WALActionsListener { int increments = 0; @Override public void visitLogEntryBeforeWrite(RegionInfo info, WALKey logKey, WALEdit logEdit) { increments++; } } @Test public void testWALProviders() throws IOException { Configuration conf = new Configuration(); WALFactory walFactory = new WALFactory(conf, this.currentServername.toString()); assertEquals(walFactory.getWALProvider().getClass(), walFactory.getMetaProvider().getClass()); // if providers are not set and do not enable SyncReplicationWALProvider walFactory = new WALFactory(conf, this.currentServername, null); assertEquals(walFactory.getWALProvider().getClass(), walFactory.getMetaProvider().getClass()); } @Test public void testOnlySetWALProvider() throws IOException { Configuration conf = new Configuration(); conf.set(WAL_PROVIDER, WALFactory.Providers.multiwal.name()); WALFactory walFactory = new WALFactory(conf, this.currentServername.toString()); // class of WALProvider and metaWALProvider are the same when metaWALProvider is not set assertEquals(WALFactory.Providers.multiwal.clazz, walFactory.getWALProvider().getClass()); assertEquals(WALFactory.Providers.multiwal.clazz, walFactory.getMetaProvider().getClass()); } @Test public void testOnlySetMetaWALProvider() throws IOException { Configuration conf = new Configuration(); conf.set(META_WAL_PROVIDER, WALFactory.Providers.asyncfs.name()); WALFactory walFactory = new WALFactory(conf, this.currentServername.toString()); assertEquals(WALFactory.Providers.defaultProvider.clazz, walFactory.getWALProvider().getClass()); assertEquals(WALFactory.Providers.asyncfs.clazz, walFactory.getMetaProvider().getClass()); } @Test public void testDefaultProvider() throws IOException { final Configuration conf = new Configuration(); // AsyncFSWal is the default, we should be able to request any WAL. final WALFactory normalWalFactory = new WALFactory(conf, this.currentServername.toString()); Class<? extends WALProvider> fshLogProvider = normalWalFactory.getProviderClass(WALFactory.WAL_PROVIDER, Providers.filesystem.name()); assertEquals(Providers.filesystem.clazz, fshLogProvider); // Imagine a world where MultiWAL is the default final WALFactory customizedWalFactory = new WALFactory(conf, this.currentServername.toString()) { @Override Providers getDefaultProvider() { return Providers.multiwal; } }; // If we don't specify a WALProvider, we should get the default implementation. Class<? extends WALProvider> multiwalProviderClass = customizedWalFactory.getProviderClass(WALFactory.WAL_PROVIDER, Providers.multiwal.name()); assertEquals(Providers.multiwal.clazz, multiwalProviderClass); } @Test public void testCustomProvider() throws IOException { final Configuration config = new Configuration(); config.set(WALFactory.WAL_PROVIDER, IOTestProvider.class.getName()); final WALFactory walFactory = new WALFactory(config, this.currentServername.toString()); Class<? extends WALProvider> walProvider = walFactory.getProviderClass(WALFactory.WAL_PROVIDER, Providers.filesystem.name()); assertEquals(IOTestProvider.class, walProvider); WALProvider metaWALProvider = walFactory.getMetaProvider(); assertEquals(IOTestProvider.class, metaWALProvider.getClass()); } @Test public void testCustomMetaProvider() throws IOException { final Configuration config = new Configuration(); config.set(WALFactory.META_WAL_PROVIDER, IOTestProvider.class.getName()); final WALFactory walFactory = new WALFactory(config, this.currentServername.toString()); Class<? extends WALProvider> walProvider = walFactory.getProviderClass(WALFactory.WAL_PROVIDER, Providers.filesystem.name()); assertEquals(Providers.filesystem.clazz, walProvider); WALProvider metaWALProvider = walFactory.getMetaProvider(); assertEquals(IOTestProvider.class, metaWALProvider.getClass()); } @Test public void testCustomReplicationProvider() throws IOException { final Configuration config = new Configuration(); config.set(WALFactory.REPLICATION_WAL_PROVIDER, IOTestProvider.class.getName()); final WALFactory walFactory = new WALFactory(config, this.currentServername.toString()); Class<? extends WALProvider> walProvider = walFactory.getProviderClass(WALFactory.WAL_PROVIDER, Providers.filesystem.name()); assertEquals(Providers.filesystem.clazz, walProvider); WALProvider replicationWALProvider = walFactory.getReplicationProvider(); assertEquals(IOTestProvider.class, replicationWALProvider.getClass()); } /** * Confirm that we will use different WALs for hbase:meta and hbase:replication */ @Test public void testDifferentWALs() throws IOException { WAL normalWAL = wals.getWAL(null); WAL metaWAL = wals.getWAL(RegionInfoBuilder.FIRST_META_REGIONINFO); WAL replicationWAL = wals.getWAL(RegionInfoBuilder .newBuilder(ReplicationStorageFactory.REPLICATION_QUEUE_TABLE_NAME_DEFAULT).build()); assertNotSame(normalWAL, metaWAL); assertNotSame(normalWAL, replicationWAL); assertNotSame(metaWAL, replicationWAL); } @Test public void testReaderClosedOnBadCodec() throws IOException { // Create our own Configuration and WALFactory to avoid breaking other test methods Configuration confWithCodec = new Configuration(conf); confWithCodec.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, BrokenWALCellCodec.class, Codec.class); WALFactory customFactory = new WALFactory(confWithCodec, this.currentServername.toString()); // Hack a Proxy over the FileSystem so that we can track the InputStreams opened by // the FileSystem and know if close() was called on those InputStreams. List<InputStreamProxy> openedReaders = new ArrayList<>(); FileSystemProxy proxyFs = new FileSystemProxy(fs) { @Override public FSDataInputStream open(Path p) throws IOException { InputStreamProxy is = new InputStreamProxy(super.open(p)); openedReaders.add(is); return is; } @Override public FSDataInputStream open(Path p, int blockSize) throws IOException { InputStreamProxy is = new InputStreamProxy(super.open(p, blockSize)); openedReaders.add(is); return is; } }; final TableDescriptor htd = TableDescriptorBuilder.newBuilder(TableName.valueOf(currentTest.getMethodName())) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("column")).build(); final RegionInfo hri = RegionInfoBuilder.newBuilder(htd.getTableName()).build(); NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); for (byte[] fam : htd.getColumnFamilyNames()) { scopes.put(fam, 0); } byte[] row = Bytes.toBytes("row"); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); // Write one column in one edit. WALEdit cols = new WALEdit(); cols.add(new KeyValue(row, Bytes.toBytes("column"), Bytes.toBytes("0"), EnvironmentEdgeManager.currentTime(), new byte[] { 0 })); final WAL log = customFactory.getWAL(hri); final long txid = log.appendData(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), htd.getTableName(), EnvironmentEdgeManager.currentTime(), mvcc, scopes), cols); // Sync the edit to the WAL log.sync(txid); log.startCacheFlush(hri.getEncodedNameAsBytes(), htd.getColumnFamilyNames()); log.completeCacheFlush(hri.getEncodedNameAsBytes(), HConstants.NO_SEQNUM); log.shutdown(); // Inject our failure, object is constructed via reflection. BrokenWALCellCodec.THROW_FAILURE_ON_INIT.set(true); // Now open a reader on the log which will throw an exception when // we try to instantiate the custom Codec. Path filename = AbstractFSWALProvider.getCurrentFileName(log); assertThrows("Expected to see an exception when creating WAL reader", IOException.class, () -> customFactory.createStreamReader(proxyFs, filename)); // We should have exactly one reader assertEquals(1, openedReaders.size()); // And that reader should be closed. long unclosedReaders = openedReaders.stream().filter((r) -> !r.isClosed.get()).collect(Collectors.counting()); assertEquals("Should not find any open readers", 0, unclosedReaders); } /** * A proxy around FSDataInputStream which can report if close() was called. */ private static class InputStreamProxy extends FSDataInputStream { private final InputStream real; private final AtomicBoolean isClosed = new AtomicBoolean(false); public InputStreamProxy(InputStream real) { super(real); this.real = real; } @Override public void close() throws IOException { isClosed.set(true); real.close(); } } /** * A custom WALCellCodec in which we can inject failure. */ @SuppressWarnings("unused") private static class BrokenWALCellCodec extends WALCellCodec { static final AtomicBoolean THROW_FAILURE_ON_INIT = new AtomicBoolean(false); static void maybeInjectFailure() { if (THROW_FAILURE_ON_INIT.get()) { throw new RuntimeException("Injected instantiation exception"); } } public BrokenWALCellCodec() { super(); maybeInjectFailure(); } public BrokenWALCellCodec(Configuration conf, CompressionContext compression) { super(conf, compression); maybeInjectFailure(); } } }
apache/xmlgraphics-batik
35,914
batik-css/src/main/java/org/apache/batik/css/engine/value/svg/ColorManager.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.css.engine.value.svg; import org.apache.batik.css.engine.value.AbstractColorManager; import org.apache.batik.css.engine.value.Value; import org.apache.batik.css.engine.value.ValueManager; import org.apache.batik.util.CSSConstants; import org.apache.batik.util.SVGTypes; /** * This class provides a manager for the 'color' property values. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class ColorManager extends AbstractColorManager { /** * The default color value. */ protected static final Value DEFAULT_VALUE = SVGValueConstants.BLACK_RGB_VALUE; // // Add some identifier values. // static { values.put(CSSConstants.CSS_ALICEBLUE_VALUE, SVGValueConstants.ALICEBLUE_VALUE); values.put(CSSConstants.CSS_ANTIQUEWHITE_VALUE, SVGValueConstants.ANTIQUEWHITE_VALUE); values.put(CSSConstants.CSS_AQUAMARINE_VALUE, SVGValueConstants.AQUAMARINE_VALUE); values.put(CSSConstants.CSS_AZURE_VALUE, SVGValueConstants.AZURE_VALUE); values.put(CSSConstants.CSS_BEIGE_VALUE, SVGValueConstants.BEIGE_VALUE); values.put(CSSConstants.CSS_BISQUE_VALUE, SVGValueConstants.BISQUE_VALUE); values.put(CSSConstants.CSS_BLANCHEDALMOND_VALUE, SVGValueConstants.BLANCHEDALMOND_VALUE); values.put(CSSConstants.CSS_BLUEVIOLET_VALUE, SVGValueConstants.BLUEVIOLET_VALUE); values.put(CSSConstants.CSS_BROWN_VALUE, SVGValueConstants.BROWN_VALUE); values.put(CSSConstants.CSS_BURLYWOOD_VALUE, SVGValueConstants.BURLYWOOD_VALUE); values.put(CSSConstants.CSS_CADETBLUE_VALUE, SVGValueConstants.CADETBLUE_VALUE); values.put(CSSConstants.CSS_CHARTREUSE_VALUE, SVGValueConstants.CHARTREUSE_VALUE); values.put(CSSConstants.CSS_CHOCOLATE_VALUE, SVGValueConstants.CHOCOLATE_VALUE); values.put(CSSConstants.CSS_CORAL_VALUE, SVGValueConstants.CORAL_VALUE); values.put(CSSConstants.CSS_CORNFLOWERBLUE_VALUE, SVGValueConstants.CORNFLOWERBLUE_VALUE); values.put(CSSConstants.CSS_CORNSILK_VALUE, SVGValueConstants.CORNSILK_VALUE); values.put(CSSConstants.CSS_CRIMSON_VALUE, SVGValueConstants.CRIMSON_VALUE); values.put(CSSConstants.CSS_CYAN_VALUE, SVGValueConstants.CYAN_VALUE); values.put(CSSConstants.CSS_DARKBLUE_VALUE, SVGValueConstants.DARKBLUE_VALUE); values.put(CSSConstants.CSS_DARKCYAN_VALUE, SVGValueConstants.DARKCYAN_VALUE); values.put(CSSConstants.CSS_DARKGOLDENROD_VALUE, SVGValueConstants.DARKGOLDENROD_VALUE); values.put(CSSConstants.CSS_DARKGRAY_VALUE, SVGValueConstants.DARKGRAY_VALUE); values.put(CSSConstants.CSS_DARKGREEN_VALUE, SVGValueConstants.DARKGREEN_VALUE); values.put(CSSConstants.CSS_DARKGREY_VALUE, SVGValueConstants.DARKGREY_VALUE); values.put(CSSConstants.CSS_DARKKHAKI_VALUE, SVGValueConstants.DARKKHAKI_VALUE); values.put(CSSConstants.CSS_DARKMAGENTA_VALUE, SVGValueConstants.DARKMAGENTA_VALUE); values.put(CSSConstants.CSS_DARKOLIVEGREEN_VALUE, SVGValueConstants.DARKOLIVEGREEN_VALUE); values.put(CSSConstants.CSS_DARKORANGE_VALUE, SVGValueConstants.DARKORANGE_VALUE); values.put(CSSConstants.CSS_DARKORCHID_VALUE, SVGValueConstants.DARKORCHID_VALUE); values.put(CSSConstants.CSS_DARKRED_VALUE, SVGValueConstants.DARKRED_VALUE); values.put(CSSConstants.CSS_DARKSALMON_VALUE, SVGValueConstants.DARKSALMON_VALUE); values.put(CSSConstants.CSS_DARKSEAGREEN_VALUE, SVGValueConstants.DARKSEAGREEN_VALUE); values.put(CSSConstants.CSS_DARKSLATEBLUE_VALUE, SVGValueConstants.DARKSLATEBLUE_VALUE); values.put(CSSConstants.CSS_DARKSLATEGRAY_VALUE, SVGValueConstants.DARKSLATEGRAY_VALUE); values.put(CSSConstants.CSS_DARKSLATEGREY_VALUE, SVGValueConstants.DARKSLATEGREY_VALUE); values.put(CSSConstants.CSS_DARKTURQUOISE_VALUE, SVGValueConstants.DARKTURQUOISE_VALUE); values.put(CSSConstants.CSS_DARKVIOLET_VALUE, SVGValueConstants.DARKVIOLET_VALUE); values.put(CSSConstants.CSS_DEEPPINK_VALUE, SVGValueConstants.DEEPPINK_VALUE); values.put(CSSConstants.CSS_DEEPSKYBLUE_VALUE, SVGValueConstants.DEEPSKYBLUE_VALUE); values.put(CSSConstants.CSS_DIMGRAY_VALUE, SVGValueConstants.DIMGRAY_VALUE); values.put(CSSConstants.CSS_DIMGREY_VALUE, SVGValueConstants.DIMGREY_VALUE); values.put(CSSConstants.CSS_DODGERBLUE_VALUE, SVGValueConstants.DODGERBLUE_VALUE); values.put(CSSConstants.CSS_FIREBRICK_VALUE, SVGValueConstants.FIREBRICK_VALUE); values.put(CSSConstants.CSS_FLORALWHITE_VALUE, SVGValueConstants.FLORALWHITE_VALUE); values.put(CSSConstants.CSS_FORESTGREEN_VALUE, SVGValueConstants.FORESTGREEN_VALUE); values.put(CSSConstants.CSS_GAINSBORO_VALUE, SVGValueConstants.GAINSBORO_VALUE); values.put(CSSConstants.CSS_GHOSTWHITE_VALUE, SVGValueConstants.GHOSTWHITE_VALUE); values.put(CSSConstants.CSS_GOLD_VALUE, SVGValueConstants.GOLD_VALUE); values.put(CSSConstants.CSS_GOLDENROD_VALUE, SVGValueConstants.GOLDENROD_VALUE); values.put(CSSConstants.CSS_GREENYELLOW_VALUE, SVGValueConstants.GREENYELLOW_VALUE); values.put(CSSConstants.CSS_GREY_VALUE, SVGValueConstants.GREY_VALUE); values.put(CSSConstants.CSS_HONEYDEW_VALUE, SVGValueConstants.HONEYDEW_VALUE); values.put(CSSConstants.CSS_HOTPINK_VALUE, SVGValueConstants.HOTPINK_VALUE); values.put(CSSConstants.CSS_INDIANRED_VALUE, SVGValueConstants.INDIANRED_VALUE); values.put(CSSConstants.CSS_INDIGO_VALUE, SVGValueConstants.INDIGO_VALUE); values.put(CSSConstants.CSS_IVORY_VALUE, SVGValueConstants.IVORY_VALUE); values.put(CSSConstants.CSS_KHAKI_VALUE, SVGValueConstants.KHAKI_VALUE); values.put(CSSConstants.CSS_LAVENDER_VALUE, SVGValueConstants.LAVENDER_VALUE); values.put(CSSConstants.CSS_LAVENDERBLUSH_VALUE, SVGValueConstants.LAVENDERBLUSH_VALUE); values.put(CSSConstants.CSS_LAWNGREEN_VALUE, SVGValueConstants.LAWNGREEN_VALUE); values.put(CSSConstants.CSS_LEMONCHIFFON_VALUE, SVGValueConstants.LEMONCHIFFON_VALUE); values.put(CSSConstants.CSS_LIGHTBLUE_VALUE, SVGValueConstants.LIGHTBLUE_VALUE); values.put(CSSConstants.CSS_LIGHTCORAL_VALUE, SVGValueConstants.LIGHTCORAL_VALUE); values.put(CSSConstants.CSS_LIGHTCYAN_VALUE, SVGValueConstants.LIGHTCYAN_VALUE); values.put(CSSConstants.CSS_LIGHTGOLDENRODYELLOW_VALUE, SVGValueConstants.LIGHTGOLDENRODYELLOW_VALUE); values.put(CSSConstants.CSS_LIGHTGRAY_VALUE, SVGValueConstants.LIGHTGRAY_VALUE); values.put(CSSConstants.CSS_LIGHTGREEN_VALUE, SVGValueConstants.LIGHTGREEN_VALUE); values.put(CSSConstants.CSS_LIGHTGREY_VALUE, SVGValueConstants.LIGHTGREY_VALUE); values.put(CSSConstants.CSS_LIGHTPINK_VALUE, SVGValueConstants.LIGHTPINK_VALUE); values.put(CSSConstants.CSS_LIGHTSALMON_VALUE, SVGValueConstants.LIGHTSALMON_VALUE); values.put(CSSConstants.CSS_LIGHTSEAGREEN_VALUE, SVGValueConstants.LIGHTSEAGREEN_VALUE); values.put(CSSConstants.CSS_LIGHTSKYBLUE_VALUE, SVGValueConstants.LIGHTSKYBLUE_VALUE); values.put(CSSConstants.CSS_LIGHTSLATEGRAY_VALUE, SVGValueConstants.LIGHTSLATEGRAY_VALUE); values.put(CSSConstants.CSS_LIGHTSLATEGREY_VALUE, SVGValueConstants.LIGHTSLATEGREY_VALUE); values.put(CSSConstants.CSS_LIGHTSTEELBLUE_VALUE, SVGValueConstants.LIGHTSTEELBLUE_VALUE); values.put(CSSConstants.CSS_LIGHTYELLOW_VALUE, SVGValueConstants.LIGHTYELLOW_VALUE); values.put(CSSConstants.CSS_LIMEGREEN_VALUE, SVGValueConstants.LIMEGREEN_VALUE); values.put(CSSConstants.CSS_LINEN_VALUE, SVGValueConstants.LINEN_VALUE); values.put(CSSConstants.CSS_MAGENTA_VALUE, SVGValueConstants.MAGENTA_VALUE); values.put(CSSConstants.CSS_MEDIUMAQUAMARINE_VALUE, SVGValueConstants.MEDIUMAQUAMARINE_VALUE); values.put(CSSConstants.CSS_MEDIUMBLUE_VALUE, SVGValueConstants.MEDIUMBLUE_VALUE); values.put(CSSConstants.CSS_MEDIUMORCHID_VALUE, SVGValueConstants.MEDIUMORCHID_VALUE); values.put(CSSConstants.CSS_MEDIUMPURPLE_VALUE, SVGValueConstants.MEDIUMPURPLE_VALUE); values.put(CSSConstants.CSS_MEDIUMSEAGREEN_VALUE, SVGValueConstants.MEDIUMSEAGREEN_VALUE); values.put(CSSConstants.CSS_MEDIUMSLATEBLUE_VALUE, SVGValueConstants.MEDIUMSLATEBLUE_VALUE); values.put(CSSConstants.CSS_MEDIUMSPRINGGREEN_VALUE, SVGValueConstants.MEDIUMSPRINGGREEN_VALUE); values.put(CSSConstants.CSS_MEDIUMTURQUOISE_VALUE, SVGValueConstants.MEDIUMTURQUOISE_VALUE); values.put(CSSConstants.CSS_MEDIUMVIOLETRED_VALUE, SVGValueConstants.MEDIUMVIOLETRED_VALUE); values.put(CSSConstants.CSS_MIDNIGHTBLUE_VALUE, SVGValueConstants.MIDNIGHTBLUE_VALUE); values.put(CSSConstants.CSS_MINTCREAM_VALUE, SVGValueConstants.MINTCREAM_VALUE); values.put(CSSConstants.CSS_MISTYROSE_VALUE, SVGValueConstants.MISTYROSE_VALUE); values.put(CSSConstants.CSS_MOCCASIN_VALUE, SVGValueConstants.MOCCASIN_VALUE); values.put(CSSConstants.CSS_NAVAJOWHITE_VALUE, SVGValueConstants.NAVAJOWHITE_VALUE); values.put(CSSConstants.CSS_OLDLACE_VALUE, SVGValueConstants.OLDLACE_VALUE); values.put(CSSConstants.CSS_OLIVEDRAB_VALUE, SVGValueConstants.OLIVEDRAB_VALUE); values.put(CSSConstants.CSS_ORANGE_VALUE, SVGValueConstants.ORANGE_VALUE); values.put(CSSConstants.CSS_ORANGERED_VALUE, SVGValueConstants.ORANGERED_VALUE); values.put(CSSConstants.CSS_ORCHID_VALUE, SVGValueConstants.ORCHID_VALUE); values.put(CSSConstants.CSS_PALEGOLDENROD_VALUE, SVGValueConstants.PALEGOLDENROD_VALUE); values.put(CSSConstants.CSS_PALEGREEN_VALUE, SVGValueConstants.PALEGREEN_VALUE); values.put(CSSConstants.CSS_PALETURQUOISE_VALUE, SVGValueConstants.PALETURQUOISE_VALUE); values.put(CSSConstants.CSS_PALEVIOLETRED_VALUE, SVGValueConstants.PALEVIOLETRED_VALUE); values.put(CSSConstants.CSS_PAPAYAWHIP_VALUE, SVGValueConstants.PAPAYAWHIP_VALUE); values.put(CSSConstants.CSS_PEACHPUFF_VALUE, SVGValueConstants.PEACHPUFF_VALUE); values.put(CSSConstants.CSS_PERU_VALUE, SVGValueConstants.PERU_VALUE); values.put(CSSConstants.CSS_PINK_VALUE, SVGValueConstants.PINK_VALUE); values.put(CSSConstants.CSS_PLUM_VALUE, SVGValueConstants.PLUM_VALUE); values.put(CSSConstants.CSS_POWDERBLUE_VALUE, SVGValueConstants.POWDERBLUE_VALUE); values.put(CSSConstants.CSS_PURPLE_VALUE, SVGValueConstants.PURPLE_VALUE); values.put(CSSConstants.CSS_ROSYBROWN_VALUE, SVGValueConstants.ROSYBROWN_VALUE); values.put(CSSConstants.CSS_ROYALBLUE_VALUE, SVGValueConstants.ROYALBLUE_VALUE); values.put(CSSConstants.CSS_SADDLEBROWN_VALUE, SVGValueConstants.SADDLEBROWN_VALUE); values.put(CSSConstants.CSS_SALMON_VALUE, SVGValueConstants.SALMON_VALUE); values.put(CSSConstants.CSS_SANDYBROWN_VALUE, SVGValueConstants.SANDYBROWN_VALUE); values.put(CSSConstants.CSS_SEAGREEN_VALUE, SVGValueConstants.SEAGREEN_VALUE); values.put(CSSConstants.CSS_SEASHELL_VALUE, SVGValueConstants.SEASHELL_VALUE); values.put(CSSConstants.CSS_SIENNA_VALUE, SVGValueConstants.SIENNA_VALUE); values.put(CSSConstants.CSS_SKYBLUE_VALUE, SVGValueConstants.SKYBLUE_VALUE); values.put(CSSConstants.CSS_SLATEBLUE_VALUE, SVGValueConstants.SLATEBLUE_VALUE); values.put(CSSConstants.CSS_SLATEGRAY_VALUE, SVGValueConstants.SLATEGRAY_VALUE); values.put(CSSConstants.CSS_SLATEGREY_VALUE, SVGValueConstants.SLATEGREY_VALUE); values.put(CSSConstants.CSS_SNOW_VALUE, SVGValueConstants.SNOW_VALUE); values.put(CSSConstants.CSS_SPRINGGREEN_VALUE, SVGValueConstants.SPRINGGREEN_VALUE); values.put(CSSConstants.CSS_STEELBLUE_VALUE, SVGValueConstants.STEELBLUE_VALUE); values.put(CSSConstants.CSS_TAN_VALUE, SVGValueConstants.TAN_VALUE); values.put(CSSConstants.CSS_THISTLE_VALUE, SVGValueConstants.THISTLE_VALUE); values.put(CSSConstants.CSS_TOMATO_VALUE, SVGValueConstants.TOMATO_VALUE); values.put(CSSConstants.CSS_TURQUOISE_VALUE, SVGValueConstants.TURQUOISE_VALUE); values.put(CSSConstants.CSS_VIOLET_VALUE, SVGValueConstants.VIOLET_VALUE); values.put(CSSConstants.CSS_WHEAT_VALUE, SVGValueConstants.WHEAT_VALUE); values.put(CSSConstants.CSS_WHITESMOKE_VALUE, SVGValueConstants.WHITESMOKE_VALUE); values.put(CSSConstants.CSS_YELLOWGREEN_VALUE, SVGValueConstants.YELLOWGREEN_VALUE); } // // Add and replace some computed colors. // static { computedValues.put(CSSConstants.CSS_BLACK_VALUE, SVGValueConstants.BLACK_RGB_VALUE); computedValues.put(CSSConstants.CSS_SILVER_VALUE, SVGValueConstants.SILVER_RGB_VALUE); computedValues.put(CSSConstants.CSS_GRAY_VALUE, SVGValueConstants.GRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_WHITE_VALUE, SVGValueConstants.WHITE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MAROON_VALUE, SVGValueConstants.MAROON_RGB_VALUE); computedValues.put(CSSConstants.CSS_RED_VALUE, SVGValueConstants.RED_RGB_VALUE); computedValues.put(CSSConstants.CSS_PURPLE_VALUE, SVGValueConstants.PURPLE_RGB_VALUE); computedValues.put(CSSConstants.CSS_FUCHSIA_VALUE, SVGValueConstants.FUCHSIA_RGB_VALUE); computedValues.put(CSSConstants.CSS_GREEN_VALUE, SVGValueConstants.GREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIME_VALUE, SVGValueConstants.LIME_RGB_VALUE); computedValues.put(CSSConstants.CSS_OLIVE_VALUE, SVGValueConstants.OLIVE_RGB_VALUE); computedValues.put(CSSConstants.CSS_YELLOW_VALUE, SVGValueConstants.YELLOW_RGB_VALUE); computedValues.put(CSSConstants.CSS_NAVY_VALUE, SVGValueConstants.NAVY_RGB_VALUE); computedValues.put(CSSConstants.CSS_BLUE_VALUE, SVGValueConstants.BLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_TEAL_VALUE, SVGValueConstants.TEAL_RGB_VALUE); computedValues.put(CSSConstants.CSS_AQUA_VALUE, SVGValueConstants.AQUA_RGB_VALUE); computedValues.put(CSSConstants.CSS_ALICEBLUE_VALUE, SVGValueConstants.ALICEBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_ANTIQUEWHITE_VALUE, SVGValueConstants.ANTIQUEWHITE_RGB_VALUE); computedValues.put(CSSConstants.CSS_AQUAMARINE_VALUE, SVGValueConstants.AQUAMARINE_RGB_VALUE); computedValues.put(CSSConstants.CSS_AZURE_VALUE, SVGValueConstants.AZURE_RGB_VALUE); computedValues.put(CSSConstants.CSS_BEIGE_VALUE, SVGValueConstants.BEIGE_RGB_VALUE); computedValues.put(CSSConstants.CSS_BISQUE_VALUE, SVGValueConstants.BISQUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_BLANCHEDALMOND_VALUE, SVGValueConstants.BLANCHEDALMOND_RGB_VALUE); computedValues.put(CSSConstants.CSS_BLUEVIOLET_VALUE, SVGValueConstants.BLUEVIOLET_RGB_VALUE); computedValues.put(CSSConstants.CSS_BROWN_VALUE, SVGValueConstants.BROWN_RGB_VALUE); computedValues.put(CSSConstants.CSS_BURLYWOOD_VALUE, SVGValueConstants.BURLYWOOD_RGB_VALUE); computedValues.put(CSSConstants.CSS_CADETBLUE_VALUE, SVGValueConstants.CADETBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_CHARTREUSE_VALUE, SVGValueConstants.CHARTREUSE_RGB_VALUE); computedValues.put(CSSConstants.CSS_CHOCOLATE_VALUE, SVGValueConstants.CHOCOLATE_RGB_VALUE); computedValues.put(CSSConstants.CSS_CORAL_VALUE, SVGValueConstants.CORAL_RGB_VALUE); computedValues.put(CSSConstants.CSS_CORNFLOWERBLUE_VALUE, SVGValueConstants.CORNFLOWERBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_CORNSILK_VALUE, SVGValueConstants.CORNSILK_RGB_VALUE); computedValues.put(CSSConstants.CSS_CRIMSON_VALUE, SVGValueConstants.CRIMSON_RGB_VALUE); computedValues.put(CSSConstants.CSS_CYAN_VALUE, SVGValueConstants.CYAN_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKBLUE_VALUE, SVGValueConstants.DARKBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKCYAN_VALUE, SVGValueConstants.DARKCYAN_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKGOLDENROD_VALUE, SVGValueConstants.DARKGOLDENROD_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKGRAY_VALUE, SVGValueConstants.DARKGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKGREEN_VALUE, SVGValueConstants.DARKGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKGREY_VALUE, SVGValueConstants.DARKGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKKHAKI_VALUE, SVGValueConstants.DARKKHAKI_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKMAGENTA_VALUE, SVGValueConstants.DARKMAGENTA_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKOLIVEGREEN_VALUE, SVGValueConstants.DARKOLIVEGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKORANGE_VALUE, SVGValueConstants.DARKORANGE_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKORCHID_VALUE, SVGValueConstants.DARKORCHID_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKRED_VALUE, SVGValueConstants.DARKRED_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKSALMON_VALUE, SVGValueConstants.DARKSALMON_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKSEAGREEN_VALUE, SVGValueConstants.DARKSEAGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKSLATEBLUE_VALUE, SVGValueConstants.DARKSLATEBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKSLATEGRAY_VALUE, SVGValueConstants.DARKSLATEGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKSLATEGREY_VALUE, SVGValueConstants.DARKSLATEGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKTURQUOISE_VALUE, SVGValueConstants.DARKTURQUOISE_RGB_VALUE); computedValues.put(CSSConstants.CSS_DARKVIOLET_VALUE, SVGValueConstants.DARKVIOLET_RGB_VALUE); computedValues.put(CSSConstants.CSS_DEEPPINK_VALUE, SVGValueConstants.DEEPPINK_RGB_VALUE); computedValues.put(CSSConstants.CSS_DEEPSKYBLUE_VALUE, SVGValueConstants.DEEPSKYBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_DIMGRAY_VALUE, SVGValueConstants.DIMGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DIMGREY_VALUE, SVGValueConstants.DIMGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_DODGERBLUE_VALUE, SVGValueConstants.DODGERBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_FIREBRICK_VALUE, SVGValueConstants.FIREBRICK_RGB_VALUE); computedValues.put(CSSConstants.CSS_FLORALWHITE_VALUE, SVGValueConstants.FLORALWHITE_RGB_VALUE); computedValues.put(CSSConstants.CSS_FORESTGREEN_VALUE, SVGValueConstants.FORESTGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_GAINSBORO_VALUE, SVGValueConstants.GAINSBORO_RGB_VALUE); computedValues.put(CSSConstants.CSS_GHOSTWHITE_VALUE, SVGValueConstants.GHOSTWHITE_RGB_VALUE); computedValues.put(CSSConstants.CSS_GOLD_VALUE, SVGValueConstants.GOLD_RGB_VALUE); computedValues.put(CSSConstants.CSS_GOLDENROD_VALUE, SVGValueConstants.GOLDENROD_RGB_VALUE); computedValues.put(CSSConstants.CSS_GREY_VALUE, SVGValueConstants.GREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_GREENYELLOW_VALUE, SVGValueConstants.GREENYELLOW_RGB_VALUE); computedValues.put(CSSConstants.CSS_HONEYDEW_VALUE, SVGValueConstants.HONEYDEW_RGB_VALUE); computedValues.put(CSSConstants.CSS_HOTPINK_VALUE, SVGValueConstants.HOTPINK_RGB_VALUE); computedValues.put(CSSConstants.CSS_INDIANRED_VALUE, SVGValueConstants.INDIANRED_RGB_VALUE); computedValues.put(CSSConstants.CSS_INDIGO_VALUE, SVGValueConstants.INDIGO_RGB_VALUE); computedValues.put(CSSConstants.CSS_IVORY_VALUE, SVGValueConstants.IVORY_RGB_VALUE); computedValues.put(CSSConstants.CSS_KHAKI_VALUE, SVGValueConstants.KHAKI_RGB_VALUE); computedValues.put(CSSConstants.CSS_LAVENDER_VALUE, SVGValueConstants.LAVENDER_RGB_VALUE); computedValues.put(CSSConstants.CSS_LAVENDERBLUSH_VALUE, SVGValueConstants.LAVENDERBLUSH_RGB_VALUE); computedValues.put(CSSConstants.CSS_LAWNGREEN_VALUE, SVGValueConstants.LAWNGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LEMONCHIFFON_VALUE, SVGValueConstants.LEMONCHIFFON_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTBLUE_VALUE, SVGValueConstants.LIGHTBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTCORAL_VALUE, SVGValueConstants.LIGHTCORAL_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTCYAN_VALUE, SVGValueConstants.LIGHTCYAN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTGOLDENRODYELLOW_VALUE, SVGValueConstants.LIGHTGOLDENRODYELLOW_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTGRAY_VALUE, SVGValueConstants.LIGHTGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTGREEN_VALUE, SVGValueConstants.LIGHTGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTGREY_VALUE, SVGValueConstants.LIGHTGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTPINK_VALUE, SVGValueConstants.LIGHTPINK_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSALMON_VALUE, SVGValueConstants.LIGHTSALMON_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSEAGREEN_VALUE, SVGValueConstants.LIGHTSEAGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSKYBLUE_VALUE, SVGValueConstants.LIGHTSKYBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSLATEGRAY_VALUE, SVGValueConstants.LIGHTSLATEGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSLATEGREY_VALUE, SVGValueConstants.LIGHTSLATEGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTSTEELBLUE_VALUE, SVGValueConstants.LIGHTSTEELBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIGHTYELLOW_VALUE, SVGValueConstants.LIGHTYELLOW_RGB_VALUE); computedValues.put(CSSConstants.CSS_LIMEGREEN_VALUE, SVGValueConstants.LIMEGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_LINEN_VALUE, SVGValueConstants.LINEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_MAGENTA_VALUE, SVGValueConstants.MAGENTA_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMAQUAMARINE_VALUE, SVGValueConstants.MEDIUMAQUAMARINE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMBLUE_VALUE, SVGValueConstants.MEDIUMBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMORCHID_VALUE, SVGValueConstants.MEDIUMORCHID_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMPURPLE_VALUE, SVGValueConstants.MEDIUMPURPLE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMSEAGREEN_VALUE, SVGValueConstants.MEDIUMSEAGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMSLATEBLUE_VALUE, SVGValueConstants.MEDIUMSLATEBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMSPRINGGREEN_VALUE, SVGValueConstants.MEDIUMSPRINGGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMTURQUOISE_VALUE, SVGValueConstants.MEDIUMTURQUOISE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MEDIUMVIOLETRED_VALUE, SVGValueConstants.MEDIUMVIOLETRED_RGB_VALUE); computedValues.put(CSSConstants.CSS_MIDNIGHTBLUE_VALUE, SVGValueConstants.MIDNIGHTBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MINTCREAM_VALUE, SVGValueConstants.MINTCREAM_RGB_VALUE); computedValues.put(CSSConstants.CSS_MISTYROSE_VALUE, SVGValueConstants.MISTYROSE_RGB_VALUE); computedValues.put(CSSConstants.CSS_MOCCASIN_VALUE, SVGValueConstants.MOCCASIN_RGB_VALUE); computedValues.put(CSSConstants.CSS_NAVAJOWHITE_VALUE, SVGValueConstants.NAVAJOWHITE_RGB_VALUE); computedValues.put(CSSConstants.CSS_OLDLACE_VALUE, SVGValueConstants.OLDLACE_RGB_VALUE); computedValues.put(CSSConstants.CSS_OLIVEDRAB_VALUE, SVGValueConstants.OLIVEDRAB_RGB_VALUE); computedValues.put(CSSConstants.CSS_ORANGE_VALUE, SVGValueConstants.ORANGE_RGB_VALUE); computedValues.put(CSSConstants.CSS_ORANGERED_VALUE, SVGValueConstants.ORANGERED_RGB_VALUE); computedValues.put(CSSConstants.CSS_ORCHID_VALUE, SVGValueConstants.ORCHID_RGB_VALUE); computedValues.put(CSSConstants.CSS_PALEGOLDENROD_VALUE, SVGValueConstants.PALEGOLDENROD_RGB_VALUE); computedValues.put(CSSConstants.CSS_PALEGREEN_VALUE, SVGValueConstants.PALEGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_PALETURQUOISE_VALUE, SVGValueConstants.PALETURQUOISE_RGB_VALUE); computedValues.put(CSSConstants.CSS_PALEVIOLETRED_VALUE, SVGValueConstants.PALEVIOLETRED_RGB_VALUE); computedValues.put(CSSConstants.CSS_PAPAYAWHIP_VALUE, SVGValueConstants.PAPAYAWHIP_RGB_VALUE); computedValues.put(CSSConstants.CSS_PEACHPUFF_VALUE, SVGValueConstants.PEACHPUFF_RGB_VALUE); computedValues.put(CSSConstants.CSS_PERU_VALUE, SVGValueConstants.PERU_RGB_VALUE); computedValues.put(CSSConstants.CSS_PINK_VALUE, SVGValueConstants.PINK_RGB_VALUE); computedValues.put(CSSConstants.CSS_PLUM_VALUE, SVGValueConstants.PLUM_RGB_VALUE); computedValues.put(CSSConstants.CSS_POWDERBLUE_VALUE, SVGValueConstants.POWDERBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_PURPLE_VALUE, SVGValueConstants.PURPLE_RGB_VALUE); computedValues.put(CSSConstants.CSS_ROSYBROWN_VALUE, SVGValueConstants.ROSYBROWN_RGB_VALUE); computedValues.put(CSSConstants.CSS_ROYALBLUE_VALUE, SVGValueConstants.ROYALBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_SADDLEBROWN_VALUE, SVGValueConstants.SADDLEBROWN_RGB_VALUE); computedValues.put(CSSConstants.CSS_SALMON_VALUE, SVGValueConstants.SALMON_RGB_VALUE); computedValues.put(CSSConstants.CSS_SANDYBROWN_VALUE, SVGValueConstants.SANDYBROWN_RGB_VALUE); computedValues.put(CSSConstants.CSS_SEAGREEN_VALUE, SVGValueConstants.SEAGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_SEASHELL_VALUE, SVGValueConstants.SEASHELL_RGB_VALUE); computedValues.put(CSSConstants.CSS_SIENNA_VALUE, SVGValueConstants.SIENNA_RGB_VALUE); computedValues.put(CSSConstants.CSS_SKYBLUE_VALUE, SVGValueConstants.SKYBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_SLATEBLUE_VALUE, SVGValueConstants.SLATEBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_SLATEGRAY_VALUE, SVGValueConstants.SLATEGRAY_RGB_VALUE); computedValues.put(CSSConstants.CSS_SLATEGREY_VALUE, SVGValueConstants.SLATEGREY_RGB_VALUE); computedValues.put(CSSConstants.CSS_SNOW_VALUE, SVGValueConstants.SNOW_RGB_VALUE); computedValues.put(CSSConstants.CSS_SPRINGGREEN_VALUE, SVGValueConstants.SPRINGGREEN_RGB_VALUE); computedValues.put(CSSConstants.CSS_STEELBLUE_VALUE, SVGValueConstants.STEELBLUE_RGB_VALUE); computedValues.put(CSSConstants.CSS_TAN_VALUE, SVGValueConstants.TAN_RGB_VALUE); computedValues.put(CSSConstants.CSS_THISTLE_VALUE, SVGValueConstants.THISTLE_RGB_VALUE); computedValues.put(CSSConstants.CSS_TOMATO_VALUE, SVGValueConstants.TOMATO_RGB_VALUE); computedValues.put(CSSConstants.CSS_TURQUOISE_VALUE, SVGValueConstants.TURQUOISE_RGB_VALUE); computedValues.put(CSSConstants.CSS_VIOLET_VALUE, SVGValueConstants.VIOLET_RGB_VALUE); computedValues.put(CSSConstants.CSS_WHEAT_VALUE, SVGValueConstants.WHEAT_RGB_VALUE); computedValues.put(CSSConstants.CSS_WHITESMOKE_VALUE, SVGValueConstants.WHITESMOKE_RGB_VALUE); computedValues.put(CSSConstants.CSS_YELLOWGREEN_VALUE, SVGValueConstants.YELLOWGREEN_RGB_VALUE); } /** * Implements {@link * org.apache.batik.css.engine.value.ValueManager#isInheritedProperty()}. */ public boolean isInheritedProperty() { return true; } /** * Implements {@link ValueManager#isAnimatableProperty()}. */ public boolean isAnimatableProperty() { return true; } /** * Implements {@link ValueManager#isAdditiveProperty()}. */ public boolean isAdditiveProperty() { return true; } /** * Implements {@link ValueManager#getPropertyType()}. */ public int getPropertyType() { return SVGTypes.TYPE_COLOR; } /** * Implements {@link * org.apache.batik.css.engine.value.ValueManager#getPropertyName()}. */ public String getPropertyName() { return CSSConstants.CSS_COLOR_PROPERTY; } /** * Implements {@link * org.apache.batik.css.engine.value.ValueManager#getDefaultValue()}. */ public Value getDefaultValue() { return DEFAULT_VALUE; } }
googleapis/google-api-java-client-services
35,678
clients/google-api-services-retail/v2/1.31.0/com/google/api/services/retail/v2/model/GoogleCloudRetailV2SearchRequest.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.retail.v2.model; /** * Request message for SearchService.Search method. * * <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 Retail 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 GoogleCloudRetailV2SearchRequest extends com.google.api.client.json.GenericJson { /** * Boost specification to boost certain products. See more details at this [user * guide](https://cloud.google.com/retail/docs/boosting). Notice that if both * ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from * both places are evaluated. If a search request matches multiple boost conditions, the final * boost score is equal to the sum of the boost scores from all matched boost conditions. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2SearchRequestBoostSpec boostSpec; /** * The branch resource name, such as * `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the * branch ID or leave this field empty, to search products under the default branch. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String branch; /** * The default filter that is applied when a user performs a search without checking any filters * on the search page. The filter applied to every search request when quality improvement such as * query expansion is needed. For example, if a query does not have enough results, an expanded * query with SearchRequest.canonical_filter will be returned as a supplement of the original * query. This field is strongly recommended to achieve high search quality. See * SearchRequest.filter for more details about filter syntax. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String canonicalFilter; /** * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic * facets. Do not set this field. The specification for dynamically generated facets. Notice that * only textual facets can be dynamically generated. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2SearchRequestDynamicFacetSpec dynamicFacetSpec; /** * Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100 * values are allowed. Otherwise, an INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2SearchRequestFacetSpec> facetSpecs; /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the products being filtered. Filter expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String filter; /** * The labels applied to a resource must meet the following requirements: * Each resource can have * multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a * minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values * can be empty and have a maximum length of 63 characters. * Keys and values can contain only * lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 * encoding, and international characters are allowed. * The key portion of a label must be * unique. However, you can use the same key with multiple resources. * Keys must start with a * lowercase letter or international character. See [Google Cloud * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) * for more details. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> labels; /** * A 0-indexed integer that specifies the current offset (that is, starting result location, * amongst the Products deemed by the API as relevant) in search results. This field is only * considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer offset; /** * The order in which products are returned. Products can be ordered by a field in an Product * object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String orderBy; /** * The categories associated with a category page. Required for category navigation queries to * achieve good search quality. The format should be the same as UserEvent.page_categories; To * represent full path of category, use '>' sign to separate different hierarchies. If '>' is part * of the category name, please replace it with other character(s). Category pages include special * pages such as sales or promotions. For instance, a special sale page may have the category * hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> pageCategories; /** * Maximum number of Products to return. If unspecified, defaults to a reasonable value. The * maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is * negative, an INVALID_ARGUMENT is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** * A page token SearchResponse.next_page_token, received from a previous SearchService.Search * call. Provide this to retrieve the subsequent page. When paginating, all other parameters * provided to SearchService.Search must match the call that provided the page token. Otherwise, * an INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** * The specification for personalization. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2SearchRequestPersonalizationSpec personalizationSpec; /** * Raw search query. If this field is empty, the request is considered a category browsing request * and returned results are based on filter and page_categories. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String query; /** * The query expansion specification that specifies the conditions under which query expansion * will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result- * size#query_expansion). * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2SearchRequestQueryExpansionSpec queryExpansionSpec; /** * The search mode of the search request. If not specified, a single search request triggers both * product search and faceted search. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String searchMode; /** * The spell correction specification that specifies the mode under which spell correction will * take effect. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2SearchRequestSpellCorrectionSpec spellCorrectionSpec; /** * User information. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2UserInfo userInfo; /** * The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or * LocalInventorys attributes. The attributes from all the matching variant Products or * LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra * query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a * fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in * "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID. * Supported keys are: * colorFamilies * price * originalPrice * discount * variantId * * inventory(place_id,price) * inventory(place_id,original_price) * * inventory(place_id,attributes.key), where key is any key in the * Product.local_inventories.attributes map. * attributes.key, where key is any key in the * Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where * id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". * * nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next- * day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id, * where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". * * customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type * "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than * these, an INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> variantRollupKeys; /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor logs in or out of the website. This * should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String visitorId; /** * Boost specification to boost certain products. See more details at this [user * guide](https://cloud.google.com/retail/docs/boosting). Notice that if both * ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from * both places are evaluated. If a search request matches multiple boost conditions, the final * boost score is equal to the sum of the boost scores from all matched boost conditions. * @return value or {@code null} for none */ public GoogleCloudRetailV2SearchRequestBoostSpec getBoostSpec() { return boostSpec; } /** * Boost specification to boost certain products. See more details at this [user * guide](https://cloud.google.com/retail/docs/boosting). Notice that if both * ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from * both places are evaluated. If a search request matches multiple boost conditions, the final * boost score is equal to the sum of the boost scores from all matched boost conditions. * @param boostSpec boostSpec or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setBoostSpec(GoogleCloudRetailV2SearchRequestBoostSpec boostSpec) { this.boostSpec = boostSpec; return this; } /** * The branch resource name, such as * `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the * branch ID or leave this field empty, to search products under the default branch. * @return value or {@code null} for none */ public java.lang.String getBranch() { return branch; } /** * The branch resource name, such as * `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the * branch ID or leave this field empty, to search products under the default branch. * @param branch branch or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setBranch(java.lang.String branch) { this.branch = branch; return this; } /** * The default filter that is applied when a user performs a search without checking any filters * on the search page. The filter applied to every search request when quality improvement such as * query expansion is needed. For example, if a query does not have enough results, an expanded * query with SearchRequest.canonical_filter will be returned as a supplement of the original * query. This field is strongly recommended to achieve high search quality. See * SearchRequest.filter for more details about filter syntax. * @return value or {@code null} for none */ public java.lang.String getCanonicalFilter() { return canonicalFilter; } /** * The default filter that is applied when a user performs a search without checking any filters * on the search page. The filter applied to every search request when quality improvement such as * query expansion is needed. For example, if a query does not have enough results, an expanded * query with SearchRequest.canonical_filter will be returned as a supplement of the original * query. This field is strongly recommended to achieve high search quality. See * SearchRequest.filter for more details about filter syntax. * @param canonicalFilter canonicalFilter or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setCanonicalFilter(java.lang.String canonicalFilter) { this.canonicalFilter = canonicalFilter; return this; } /** * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic * facets. Do not set this field. The specification for dynamically generated facets. Notice that * only textual facets can be dynamically generated. * @return value or {@code null} for none */ public GoogleCloudRetailV2SearchRequestDynamicFacetSpec getDynamicFacetSpec() { return dynamicFacetSpec; } /** * Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic * facets. Do not set this field. The specification for dynamically generated facets. Notice that * only textual facets can be dynamically generated. * @param dynamicFacetSpec dynamicFacetSpec or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setDynamicFacetSpec(GoogleCloudRetailV2SearchRequestDynamicFacetSpec dynamicFacetSpec) { this.dynamicFacetSpec = dynamicFacetSpec; return this; } /** * Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100 * values are allowed. Otherwise, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2SearchRequestFacetSpec> getFacetSpecs() { return facetSpecs; } /** * Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100 * values are allowed. Otherwise, an INVALID_ARGUMENT error is returned. * @param facetSpecs facetSpecs or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setFacetSpecs(java.util.List<GoogleCloudRetailV2SearchRequestFacetSpec> facetSpecs) { this.facetSpecs = facetSpecs; return this; } /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the products being filtered. Filter expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * @return value or {@code null} for none */ public java.lang.String getFilter() { return filter; } /** * The filter syntax consists of an expression language for constructing a predicate from one or * more fields of the products being filtered. Filter expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * @param filter filter or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setFilter(java.lang.String filter) { this.filter = filter; return this; } /** * The labels applied to a resource must meet the following requirements: * Each resource can have * multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a * minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values * can be empty and have a maximum length of 63 characters. * Keys and values can contain only * lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 * encoding, and international characters are allowed. * The key portion of a label must be * unique. However, you can use the same key with multiple resources. * Keys must start with a * lowercase letter or international character. See [Google Cloud * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) * for more details. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getLabels() { return labels; } /** * The labels applied to a resource must meet the following requirements: * Each resource can have * multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a * minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values * can be empty and have a maximum length of 63 characters. * Keys and values can contain only * lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 * encoding, and international characters are allowed. * The key portion of a label must be * unique. However, you can use the same key with multiple resources. * Keys must start with a * lowercase letter or international character. See [Google Cloud * Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) * for more details. * @param labels labels or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setLabels(java.util.Map<String, java.lang.String> labels) { this.labels = labels; return this; } /** * A 0-indexed integer that specifies the current offset (that is, starting result location, * amongst the Products deemed by the API as relevant) in search results. This field is only * considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned. * @return value or {@code null} for none */ public java.lang.Integer getOffset() { return offset; } /** * A 0-indexed integer that specifies the current offset (that is, starting result location, * amongst the Products deemed by the API as relevant) in search results. This field is only * considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned. * @param offset offset or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setOffset(java.lang.Integer offset) { this.offset = offset; return this; } /** * The order in which products are returned. Products can be ordered by a field in an Product * object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * @return value or {@code null} for none */ public java.lang.String getOrderBy() { return orderBy; } /** * The order in which products are returned. Products can be ordered by a field in an Product * object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more * details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If * this field is unrecognizable, an INVALID_ARGUMENT is returned. * @param orderBy orderBy or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; return this; } /** * The categories associated with a category page. Required for category navigation queries to * achieve good search quality. The format should be the same as UserEvent.page_categories; To * represent full path of category, use '>' sign to separate different hierarchies. If '>' is part * of the category name, please replace it with other character(s). Category pages include special * pages such as sales or promotions. For instance, a special sale page may have the category * hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"]. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPageCategories() { return pageCategories; } /** * The categories associated with a category page. Required for category navigation queries to * achieve good search quality. The format should be the same as UserEvent.page_categories; To * represent full path of category, use '>' sign to separate different hierarchies. If '>' is part * of the category name, please replace it with other character(s). Category pages include special * pages such as sales or promotions. For instance, a special sale page may have the category * hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"]. * @param pageCategories pageCategories or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setPageCategories(java.util.List<java.lang.String> pageCategories) { this.pageCategories = pageCategories; return this; } /** * Maximum number of Products to return. If unspecified, defaults to a reasonable value. The * maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is * negative, an INVALID_ARGUMENT is returned. * @return value or {@code null} for none */ public java.lang.Integer getPageSize() { return pageSize; } /** * Maximum number of Products to return. If unspecified, defaults to a reasonable value. The * maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is * negative, an INVALID_ARGUMENT is returned. * @param pageSize pageSize or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A page token SearchResponse.next_page_token, received from a previous SearchService.Search * call. Provide this to retrieve the subsequent page. When paginating, all other parameters * provided to SearchService.Search must match the call that provided the page token. Otherwise, * an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.lang.String getPageToken() { return pageToken; } /** * A page token SearchResponse.next_page_token, received from a previous SearchService.Search * call. Provide this to retrieve the subsequent page. When paginating, all other parameters * provided to SearchService.Search must match the call that provided the page token. Otherwise, * an INVALID_ARGUMENT error is returned. * @param pageToken pageToken or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } /** * The specification for personalization. * @return value or {@code null} for none */ public GoogleCloudRetailV2SearchRequestPersonalizationSpec getPersonalizationSpec() { return personalizationSpec; } /** * The specification for personalization. * @param personalizationSpec personalizationSpec or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setPersonalizationSpec(GoogleCloudRetailV2SearchRequestPersonalizationSpec personalizationSpec) { this.personalizationSpec = personalizationSpec; return this; } /** * Raw search query. If this field is empty, the request is considered a category browsing request * and returned results are based on filter and page_categories. * @return value or {@code null} for none */ public java.lang.String getQuery() { return query; } /** * Raw search query. If this field is empty, the request is considered a category browsing request * and returned results are based on filter and page_categories. * @param query query or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setQuery(java.lang.String query) { this.query = query; return this; } /** * The query expansion specification that specifies the conditions under which query expansion * will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result- * size#query_expansion). * @return value or {@code null} for none */ public GoogleCloudRetailV2SearchRequestQueryExpansionSpec getQueryExpansionSpec() { return queryExpansionSpec; } /** * The query expansion specification that specifies the conditions under which query expansion * will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result- * size#query_expansion). * @param queryExpansionSpec queryExpansionSpec or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setQueryExpansionSpec(GoogleCloudRetailV2SearchRequestQueryExpansionSpec queryExpansionSpec) { this.queryExpansionSpec = queryExpansionSpec; return this; } /** * The search mode of the search request. If not specified, a single search request triggers both * product search and faceted search. * @return value or {@code null} for none */ public java.lang.String getSearchMode() { return searchMode; } /** * The search mode of the search request. If not specified, a single search request triggers both * product search and faceted search. * @param searchMode searchMode or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setSearchMode(java.lang.String searchMode) { this.searchMode = searchMode; return this; } /** * The spell correction specification that specifies the mode under which spell correction will * take effect. * @return value or {@code null} for none */ public GoogleCloudRetailV2SearchRequestSpellCorrectionSpec getSpellCorrectionSpec() { return spellCorrectionSpec; } /** * The spell correction specification that specifies the mode under which spell correction will * take effect. * @param spellCorrectionSpec spellCorrectionSpec or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setSpellCorrectionSpec(GoogleCloudRetailV2SearchRequestSpellCorrectionSpec spellCorrectionSpec) { this.spellCorrectionSpec = spellCorrectionSpec; return this; } /** * User information. * @return value or {@code null} for none */ public GoogleCloudRetailV2UserInfo getUserInfo() { return userInfo; } /** * User information. * @param userInfo userInfo or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setUserInfo(GoogleCloudRetailV2UserInfo userInfo) { this.userInfo = userInfo; return this; } /** * The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or * LocalInventorys attributes. The attributes from all the matching variant Products or * LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra * query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a * fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in * "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID. * Supported keys are: * colorFamilies * price * originalPrice * discount * variantId * * inventory(place_id,price) * inventory(place_id,original_price) * * inventory(place_id,attributes.key), where key is any key in the * Product.local_inventories.attributes map. * attributes.key, where key is any key in the * Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where * id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". * * nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next- * day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id, * where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". * * customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type * "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than * these, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getVariantRollupKeys() { return variantRollupKeys; } /** * The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or * LocalInventorys attributes. The attributes from all the matching variant Products or * LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra * query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a * fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in * "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID. * Supported keys are: * colorFamilies * price * originalPrice * discount * variantId * * inventory(place_id,price) * inventory(place_id,original_price) * * inventory(place_id,attributes.key), where key is any key in the * Product.local_inventories.attributes map. * attributes.key, where key is any key in the * Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where * id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". * * nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next- * day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any * FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id, * where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". * * customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type * "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for * FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than * these, an INVALID_ARGUMENT error is returned. * @param variantRollupKeys variantRollupKeys or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setVariantRollupKeys(java.util.List<java.lang.String> variantRollupKeys) { this.variantRollupKeys = variantRollupKeys; return this; } /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor logs in or out of the website. This * should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.lang.String getVisitorId() { return visitorId; } /** * Required. A unique identifier for tracking visitors. For example, this could be implemented * with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. * This unique identifier should not change if the visitor logs in or out of the website. This * should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. * @param visitorId visitorId or {@code null} for none */ public GoogleCloudRetailV2SearchRequest setVisitorId(java.lang.String visitorId) { this.visitorId = visitorId; return this; } @Override public GoogleCloudRetailV2SearchRequest set(String fieldName, Object value) { return (GoogleCloudRetailV2SearchRequest) super.set(fieldName, value); } @Override public GoogleCloudRetailV2SearchRequest clone() { return (GoogleCloudRetailV2SearchRequest) super.clone(); } }
googleapis/google-cloud-java
35,343
java-artifact-registry/proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/ListFilesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/artifactregistry/v1/file.proto // Protobuf Java Version: 3.25.8 package com.google.devtools.artifactregistry.v1; /** * * * <pre> * The response from listing files. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListFilesResponse} */ public final class ListFilesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1.ListFilesResponse) ListFilesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListFilesResponse.newBuilder() to construct. private ListFilesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListFilesResponse() { files_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListFilesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.FileProto .internal_static_google_devtools_artifactregistry_v1_ListFilesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.FileProto .internal_static_google_devtools_artifactregistry_v1_ListFilesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListFilesResponse.class, com.google.devtools.artifactregistry.v1.ListFilesResponse.Builder.class); } public static final int FILES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.devtools.artifactregistry.v1.File> files_; /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ @java.lang.Override public java.util.List<com.google.devtools.artifactregistry.v1.File> getFilesList() { return files_; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.devtools.artifactregistry.v1.FileOrBuilder> getFilesOrBuilderList() { return files_; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ @java.lang.Override public int getFilesCount() { return files_.size(); } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.File getFiles(int index) { return files_.get(index); } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.FileOrBuilder getFilesOrBuilder(int index) { return files_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < files_.size(); i++) { output.writeMessage(1, files_.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 < files_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, files_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.devtools.artifactregistry.v1.ListFilesResponse)) { return super.equals(obj); } com.google.devtools.artifactregistry.v1.ListFilesResponse other = (com.google.devtools.artifactregistry.v1.ListFilesResponse) obj; if (!getFilesList().equals(other.getFilesList())) 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 (getFilesCount() > 0) { hash = (37 * hash) + FILES_FIELD_NUMBER; hash = (53 * hash) + getFilesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.devtools.artifactregistry.v1.ListFilesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response from listing files. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListFilesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1.ListFilesResponse) com.google.devtools.artifactregistry.v1.ListFilesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.FileProto .internal_static_google_devtools_artifactregistry_v1_ListFilesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.FileProto .internal_static_google_devtools_artifactregistry_v1_ListFilesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListFilesResponse.class, com.google.devtools.artifactregistry.v1.ListFilesResponse.Builder.class); } // Construct using com.google.devtools.artifactregistry.v1.ListFilesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (filesBuilder_ == null) { files_ = java.util.Collections.emptyList(); } else { files_ = null; filesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.devtools.artifactregistry.v1.FileProto .internal_static_google_devtools_artifactregistry_v1_ListFilesResponse_descriptor; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListFilesResponse getDefaultInstanceForType() { return com.google.devtools.artifactregistry.v1.ListFilesResponse.getDefaultInstance(); } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListFilesResponse build() { com.google.devtools.artifactregistry.v1.ListFilesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListFilesResponse buildPartial() { com.google.devtools.artifactregistry.v1.ListFilesResponse result = new com.google.devtools.artifactregistry.v1.ListFilesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.devtools.artifactregistry.v1.ListFilesResponse result) { if (filesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { files_ = java.util.Collections.unmodifiableList(files_); bitField0_ = (bitField0_ & ~0x00000001); } result.files_ = files_; } else { result.files_ = filesBuilder_.build(); } } private void buildPartial0(com.google.devtools.artifactregistry.v1.ListFilesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.devtools.artifactregistry.v1.ListFilesResponse) { return mergeFrom((com.google.devtools.artifactregistry.v1.ListFilesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.devtools.artifactregistry.v1.ListFilesResponse other) { if (other == com.google.devtools.artifactregistry.v1.ListFilesResponse.getDefaultInstance()) return this; if (filesBuilder_ == null) { if (!other.files_.isEmpty()) { if (files_.isEmpty()) { files_ = other.files_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureFilesIsMutable(); files_.addAll(other.files_); } onChanged(); } } else { if (!other.files_.isEmpty()) { if (filesBuilder_.isEmpty()) { filesBuilder_.dispose(); filesBuilder_ = null; files_ = other.files_; bitField0_ = (bitField0_ & ~0x00000001); filesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFilesFieldBuilder() : null; } else { filesBuilder_.addAllMessages(other.files_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.devtools.artifactregistry.v1.File m = input.readMessage( com.google.devtools.artifactregistry.v1.File.parser(), extensionRegistry); if (filesBuilder_ == null) { ensureFilesIsMutable(); files_.add(m); } else { filesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.devtools.artifactregistry.v1.File> files_ = java.util.Collections.emptyList(); private void ensureFilesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { files_ = new java.util.ArrayList<com.google.devtools.artifactregistry.v1.File>(files_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.File, com.google.devtools.artifactregistry.v1.File.Builder, com.google.devtools.artifactregistry.v1.FileOrBuilder> filesBuilder_; /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.File> getFilesList() { if (filesBuilder_ == null) { return java.util.Collections.unmodifiableList(files_); } else { return filesBuilder_.getMessageList(); } } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public int getFilesCount() { if (filesBuilder_ == null) { return files_.size(); } else { return filesBuilder_.getCount(); } } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public com.google.devtools.artifactregistry.v1.File getFiles(int index) { if (filesBuilder_ == null) { return files_.get(index); } else { return filesBuilder_.getMessage(index); } } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder setFiles(int index, com.google.devtools.artifactregistry.v1.File value) { if (filesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFilesIsMutable(); files_.set(index, value); onChanged(); } else { filesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder setFiles( int index, com.google.devtools.artifactregistry.v1.File.Builder builderForValue) { if (filesBuilder_ == null) { ensureFilesIsMutable(); files_.set(index, builderForValue.build()); onChanged(); } else { filesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder addFiles(com.google.devtools.artifactregistry.v1.File value) { if (filesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFilesIsMutable(); files_.add(value); onChanged(); } else { filesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder addFiles(int index, com.google.devtools.artifactregistry.v1.File value) { if (filesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFilesIsMutable(); files_.add(index, value); onChanged(); } else { filesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder addFiles(com.google.devtools.artifactregistry.v1.File.Builder builderForValue) { if (filesBuilder_ == null) { ensureFilesIsMutable(); files_.add(builderForValue.build()); onChanged(); } else { filesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder addFiles( int index, com.google.devtools.artifactregistry.v1.File.Builder builderForValue) { if (filesBuilder_ == null) { ensureFilesIsMutable(); files_.add(index, builderForValue.build()); onChanged(); } else { filesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder addAllFiles( java.lang.Iterable<? extends com.google.devtools.artifactregistry.v1.File> values) { if (filesBuilder_ == null) { ensureFilesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, files_); onChanged(); } else { filesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder clearFiles() { if (filesBuilder_ == null) { files_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { filesBuilder_.clear(); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public Builder removeFiles(int index) { if (filesBuilder_ == null) { ensureFilesIsMutable(); files_.remove(index); onChanged(); } else { filesBuilder_.remove(index); } return this; } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public com.google.devtools.artifactregistry.v1.File.Builder getFilesBuilder(int index) { return getFilesFieldBuilder().getBuilder(index); } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public com.google.devtools.artifactregistry.v1.FileOrBuilder getFilesOrBuilder(int index) { if (filesBuilder_ == null) { return files_.get(index); } else { return filesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public java.util.List<? extends com.google.devtools.artifactregistry.v1.FileOrBuilder> getFilesOrBuilderList() { if (filesBuilder_ != null) { return filesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(files_); } } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public com.google.devtools.artifactregistry.v1.File.Builder addFilesBuilder() { return getFilesFieldBuilder() .addBuilder(com.google.devtools.artifactregistry.v1.File.getDefaultInstance()); } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public com.google.devtools.artifactregistry.v1.File.Builder addFilesBuilder(int index) { return getFilesFieldBuilder() .addBuilder(index, com.google.devtools.artifactregistry.v1.File.getDefaultInstance()); } /** * * * <pre> * The files returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.File files = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.File.Builder> getFilesBuilderList() { return getFilesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.File, com.google.devtools.artifactregistry.v1.File.Builder, com.google.devtools.artifactregistry.v1.FileOrBuilder> getFilesFieldBuilder() { if (filesBuilder_ == null) { filesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.File, com.google.devtools.artifactregistry.v1.File.Builder, com.google.devtools.artifactregistry.v1.FileOrBuilder>( files_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); files_ = null; } return filesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of files, or empty if there are no * more files to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1.ListFilesResponse) } // @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1.ListFilesResponse) private static final com.google.devtools.artifactregistry.v1.ListFilesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1.ListFilesResponse(); } public static com.google.devtools.artifactregistry.v1.ListFilesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListFilesResponse> PARSER = new com.google.protobuf.AbstractParser<ListFilesResponse>() { @java.lang.Override public ListFilesResponse 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<ListFilesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListFilesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListFilesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
35,343
java-artifact-registry/proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/ListRulesResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/artifactregistry/v1/rule.proto // Protobuf Java Version: 3.25.8 package com.google.devtools.artifactregistry.v1; /** * * * <pre> * The response from listing rules. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListRulesResponse} */ public final class ListRulesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1.ListRulesResponse) ListRulesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListRulesResponse.newBuilder() to construct. private ListRulesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListRulesResponse() { rules_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListRulesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.RuleProto .internal_static_google_devtools_artifactregistry_v1_ListRulesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.RuleProto .internal_static_google_devtools_artifactregistry_v1_ListRulesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListRulesResponse.class, com.google.devtools.artifactregistry.v1.ListRulesResponse.Builder.class); } public static final int RULES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.devtools.artifactregistry.v1.Rule> rules_; /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ @java.lang.Override public java.util.List<com.google.devtools.artifactregistry.v1.Rule> getRulesList() { return rules_; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.devtools.artifactregistry.v1.RuleOrBuilder> getRulesOrBuilderList() { return rules_; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ @java.lang.Override public int getRulesCount() { return rules_.size(); } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.Rule getRules(int index) { return rules_.get(index); } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ @java.lang.Override public com.google.devtools.artifactregistry.v1.RuleOrBuilder getRulesOrBuilder(int index) { return rules_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < rules_.size(); i++) { output.writeMessage(1, rules_.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 < rules_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, rules_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.devtools.artifactregistry.v1.ListRulesResponse)) { return super.equals(obj); } com.google.devtools.artifactregistry.v1.ListRulesResponse other = (com.google.devtools.artifactregistry.v1.ListRulesResponse) obj; if (!getRulesList().equals(other.getRulesList())) 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 (getRulesCount() > 0) { hash = (37 * hash) + RULES_FIELD_NUMBER; hash = (53 * hash) + getRulesList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.devtools.artifactregistry.v1.ListRulesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The response from listing rules. * </pre> * * Protobuf type {@code google.devtools.artifactregistry.v1.ListRulesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1.ListRulesResponse) com.google.devtools.artifactregistry.v1.ListRulesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.artifactregistry.v1.RuleProto .internal_static_google_devtools_artifactregistry_v1_ListRulesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.artifactregistry.v1.RuleProto .internal_static_google_devtools_artifactregistry_v1_ListRulesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.artifactregistry.v1.ListRulesResponse.class, com.google.devtools.artifactregistry.v1.ListRulesResponse.Builder.class); } // Construct using com.google.devtools.artifactregistry.v1.ListRulesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (rulesBuilder_ == null) { rules_ = java.util.Collections.emptyList(); } else { rules_ = null; rulesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.devtools.artifactregistry.v1.RuleProto .internal_static_google_devtools_artifactregistry_v1_ListRulesResponse_descriptor; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListRulesResponse getDefaultInstanceForType() { return com.google.devtools.artifactregistry.v1.ListRulesResponse.getDefaultInstance(); } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListRulesResponse build() { com.google.devtools.artifactregistry.v1.ListRulesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListRulesResponse buildPartial() { com.google.devtools.artifactregistry.v1.ListRulesResponse result = new com.google.devtools.artifactregistry.v1.ListRulesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.devtools.artifactregistry.v1.ListRulesResponse result) { if (rulesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { rules_ = java.util.Collections.unmodifiableList(rules_); bitField0_ = (bitField0_ & ~0x00000001); } result.rules_ = rules_; } else { result.rules_ = rulesBuilder_.build(); } } private void buildPartial0(com.google.devtools.artifactregistry.v1.ListRulesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.devtools.artifactregistry.v1.ListRulesResponse) { return mergeFrom((com.google.devtools.artifactregistry.v1.ListRulesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.devtools.artifactregistry.v1.ListRulesResponse other) { if (other == com.google.devtools.artifactregistry.v1.ListRulesResponse.getDefaultInstance()) return this; if (rulesBuilder_ == null) { if (!other.rules_.isEmpty()) { if (rules_.isEmpty()) { rules_ = other.rules_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureRulesIsMutable(); rules_.addAll(other.rules_); } onChanged(); } } else { if (!other.rules_.isEmpty()) { if (rulesBuilder_.isEmpty()) { rulesBuilder_.dispose(); rulesBuilder_ = null; rules_ = other.rules_; bitField0_ = (bitField0_ & ~0x00000001); rulesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRulesFieldBuilder() : null; } else { rulesBuilder_.addAllMessages(other.rules_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.devtools.artifactregistry.v1.Rule m = input.readMessage( com.google.devtools.artifactregistry.v1.Rule.parser(), extensionRegistry); if (rulesBuilder_ == null) { ensureRulesIsMutable(); rules_.add(m); } else { rulesBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.devtools.artifactregistry.v1.Rule> rules_ = java.util.Collections.emptyList(); private void ensureRulesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { rules_ = new java.util.ArrayList<com.google.devtools.artifactregistry.v1.Rule>(rules_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.Rule, com.google.devtools.artifactregistry.v1.Rule.Builder, com.google.devtools.artifactregistry.v1.RuleOrBuilder> rulesBuilder_; /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.Rule> getRulesList() { if (rulesBuilder_ == null) { return java.util.Collections.unmodifiableList(rules_); } else { return rulesBuilder_.getMessageList(); } } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public int getRulesCount() { if (rulesBuilder_ == null) { return rules_.size(); } else { return rulesBuilder_.getCount(); } } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public com.google.devtools.artifactregistry.v1.Rule getRules(int index) { if (rulesBuilder_ == null) { return rules_.get(index); } else { return rulesBuilder_.getMessage(index); } } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder setRules(int index, com.google.devtools.artifactregistry.v1.Rule value) { if (rulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRulesIsMutable(); rules_.set(index, value); onChanged(); } else { rulesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder setRules( int index, com.google.devtools.artifactregistry.v1.Rule.Builder builderForValue) { if (rulesBuilder_ == null) { ensureRulesIsMutable(); rules_.set(index, builderForValue.build()); onChanged(); } else { rulesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder addRules(com.google.devtools.artifactregistry.v1.Rule value) { if (rulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRulesIsMutable(); rules_.add(value); onChanged(); } else { rulesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder addRules(int index, com.google.devtools.artifactregistry.v1.Rule value) { if (rulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRulesIsMutable(); rules_.add(index, value); onChanged(); } else { rulesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder addRules(com.google.devtools.artifactregistry.v1.Rule.Builder builderForValue) { if (rulesBuilder_ == null) { ensureRulesIsMutable(); rules_.add(builderForValue.build()); onChanged(); } else { rulesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder addRules( int index, com.google.devtools.artifactregistry.v1.Rule.Builder builderForValue) { if (rulesBuilder_ == null) { ensureRulesIsMutable(); rules_.add(index, builderForValue.build()); onChanged(); } else { rulesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder addAllRules( java.lang.Iterable<? extends com.google.devtools.artifactregistry.v1.Rule> values) { if (rulesBuilder_ == null) { ensureRulesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, rules_); onChanged(); } else { rulesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder clearRules() { if (rulesBuilder_ == null) { rules_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { rulesBuilder_.clear(); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public Builder removeRules(int index) { if (rulesBuilder_ == null) { ensureRulesIsMutable(); rules_.remove(index); onChanged(); } else { rulesBuilder_.remove(index); } return this; } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public com.google.devtools.artifactregistry.v1.Rule.Builder getRulesBuilder(int index) { return getRulesFieldBuilder().getBuilder(index); } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public com.google.devtools.artifactregistry.v1.RuleOrBuilder getRulesOrBuilder(int index) { if (rulesBuilder_ == null) { return rules_.get(index); } else { return rulesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public java.util.List<? extends com.google.devtools.artifactregistry.v1.RuleOrBuilder> getRulesOrBuilderList() { if (rulesBuilder_ != null) { return rulesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rules_); } } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public com.google.devtools.artifactregistry.v1.Rule.Builder addRulesBuilder() { return getRulesFieldBuilder() .addBuilder(com.google.devtools.artifactregistry.v1.Rule.getDefaultInstance()); } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public com.google.devtools.artifactregistry.v1.Rule.Builder addRulesBuilder(int index) { return getRulesFieldBuilder() .addBuilder(index, com.google.devtools.artifactregistry.v1.Rule.getDefaultInstance()); } /** * * * <pre> * The rules returned. * </pre> * * <code>repeated .google.devtools.artifactregistry.v1.Rule rules = 1;</code> */ public java.util.List<com.google.devtools.artifactregistry.v1.Rule.Builder> getRulesBuilderList() { return getRulesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.Rule, com.google.devtools.artifactregistry.v1.Rule.Builder, com.google.devtools.artifactregistry.v1.RuleOrBuilder> getRulesFieldBuilder() { if (rulesBuilder_ == null) { rulesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.devtools.artifactregistry.v1.Rule, com.google.devtools.artifactregistry.v1.Rule.Builder, com.google.devtools.artifactregistry.v1.RuleOrBuilder>( rules_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); rules_ = null; } return rulesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The token to retrieve the next page of rules, or empty if there are no * more rules to return. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1.ListRulesResponse) } // @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1.ListRulesResponse) private static final com.google.devtools.artifactregistry.v1.ListRulesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1.ListRulesResponse(); } public static com.google.devtools.artifactregistry.v1.ListRulesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListRulesResponse> PARSER = new com.google.protobuf.AbstractParser<ListRulesResponse>() { @java.lang.Override public ListRulesResponse 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<ListRulesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListRulesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.devtools.artifactregistry.v1.ListRulesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
35,756
compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/nodes/PiNode.java
/* * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.graal.compiler.nodes; import static jdk.graal.compiler.nodeinfo.NodeCycles.CYCLES_0; import static jdk.graal.compiler.nodeinfo.NodeSize.SIZE_0; import java.util.List; import jdk.graal.compiler.core.common.SuppressFBWarnings; import jdk.graal.compiler.core.common.type.AbstractPointerStamp; import jdk.graal.compiler.core.common.type.FloatStamp; import jdk.graal.compiler.core.common.type.ObjectStamp; import jdk.graal.compiler.core.common.type.Stamp; import jdk.graal.compiler.core.common.type.StampFactory; import jdk.graal.compiler.core.common.type.TypeReference; import jdk.graal.compiler.debug.Assertions; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.debug.GraalError; import jdk.graal.compiler.graph.IterableNodeType; import jdk.graal.compiler.graph.Node; import jdk.graal.compiler.graph.Node.NodeIntrinsicFactory; import jdk.graal.compiler.graph.NodeClass; import jdk.graal.compiler.nodeinfo.NodeInfo; import jdk.graal.compiler.nodes.extended.GuardingNode; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderContext; import jdk.graal.compiler.nodes.memory.ReadNode; import jdk.graal.compiler.nodes.spi.Canonicalizable; import jdk.graal.compiler.nodes.spi.CanonicalizerTool; import jdk.graal.compiler.nodes.spi.LIRLowerable; import jdk.graal.compiler.nodes.spi.NodeLIRBuilderTool; import jdk.graal.compiler.nodes.spi.SimplifierTool; import jdk.graal.compiler.nodes.spi.ValueProxy; import jdk.graal.compiler.nodes.spi.Virtualizable; import jdk.graal.compiler.nodes.spi.VirtualizerTool; import jdk.graal.compiler.nodes.type.StampTool; import jdk.graal.compiler.nodes.virtual.VirtualObjectNode; import jdk.graal.compiler.phases.common.ConditionalEliminationPhase; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.ResolvedJavaType; //JaCoCo Exclude /** * A node that changes the type of its input, usually narrowing it. For example, a {@link PiNode} * refines the type of a receiver during type-guarded inlining to be the type tested by the guard. * * In contrast to a {@link GuardedValueNode}, a {@link PiNode} is useless as soon as the type of its * input is as narrow or narrower than the {@link PiNode}'s type. The {@link PiNode}, and therefore * also the scheduling restriction enforced by the guard, will go away. */ @NodeInfo(cycles = CYCLES_0, size = SIZE_0) @NodeIntrinsicFactory public class PiNode extends FloatingGuardedNode implements LIRLowerable, Virtualizable, Canonicalizable, ValueProxy, IterableNodeType { public static final NodeClass<PiNode> TYPE = NodeClass.create(PiNode.class); @Input ValueNode object; protected Stamp piStamp; public ValueNode object() { return object; } @SuppressWarnings("this-escape") protected PiNode(NodeClass<? extends PiNode> c, ValueNode object, Stamp stamp, GuardingNode guard) { super(c, stamp, guard); this.object = object; this.piStamp = stamp; assert piStamp.isCompatible(object.stamp(NodeView.DEFAULT)) : "Object stamp not compatible to piStamp"; inferStamp(); } public PiNode(ValueNode object, Stamp stamp) { this(object, stamp, null); } public PiNode(ValueNode object, Stamp stamp, ValueNode guard) { this(TYPE, object, stamp, (GuardingNode) guard); } public PiNode(ValueNode object, ValueNode guard) { this(object, AbstractPointerStamp.pointerNonNull(object.stamp(NodeView.DEFAULT)), guard); } public PiNode(ValueNode object, ResolvedJavaType toType, boolean exactType, boolean nonNull) { this(object, StampFactory.object(exactType ? TypeReference.createExactTrusted(toType) : TypeReference.createWithoutAssumptions(toType), nonNull || StampTool.isPointerNonNull(object.stamp(NodeView.DEFAULT)))); } public static ValueNode create(ValueNode object, Stamp stamp) { ValueNode value = canonical(object, stamp, null, null); if (value != null) { return value; } return new PiNode(object, stamp); } public static ValueNode create(ValueNode object, Stamp stamp, ValueNode guard) { ValueNode value = canonical(object, stamp, (GuardingNode) guard, null); if (value != null) { return value; } return new PiNode(object, stamp, guard); } public static ValueNode create(ValueNode object, ValueNode guard) { Stamp stamp = AbstractPointerStamp.pointerNonNull(object.stamp(NodeView.DEFAULT)); ValueNode value = canonical(object, stamp, (GuardingNode) guard, null); if (value != null) { return value; } return new PiNode(object, stamp, guard); } public enum IntrinsifyOp { NON_NULL, POSITIVE_INT, INT_NON_ZERO, LONG_NON_ZERO, DOUBLE_NON_NAN, FLOAT_NON_NAN } public static boolean intrinsify(GraphBuilderContext b, ValueNode input, ValueNode guard, IntrinsifyOp intrinsifyOp) { Stamp piStamp; JavaKind pushKind; switch (intrinsifyOp) { case NON_NULL: piStamp = AbstractPointerStamp.pointerNonNull(input.stamp(NodeView.DEFAULT)); pushKind = JavaKind.Object; break; case POSITIVE_INT: piStamp = StampFactory.positiveInt(); pushKind = JavaKind.Int; break; case INT_NON_ZERO: piStamp = StampFactory.nonZeroInt(); pushKind = JavaKind.Int; break; case LONG_NON_ZERO: piStamp = StampFactory.nonZeroLong(); pushKind = JavaKind.Long; break; case FLOAT_NON_NAN: // non NAN float stamp piStamp = FloatStamp.create(Float.SIZE, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, true); pushKind = JavaKind.Float; break; case DOUBLE_NON_NAN: // non NAN double stamp piStamp = FloatStamp.create(Double.SIZE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true); pushKind = JavaKind.Double; break; default: throw GraalError.shouldNotReachHereUnexpectedValue(intrinsifyOp); // ExcludeFromJacocoGeneratedReport } ValueNode value = canonical(input, piStamp, (GuardingNode) guard, null); if (value == null) { value = new PiNode(input, piStamp, guard); } b.push(pushKind, b.append(value)); return true; } public static boolean intrinsify(GraphBuilderContext b, ValueNode object, ResolvedJavaType toType, boolean exactType, boolean nonNull, ValueNode guard) { Stamp stamp = StampFactory.object(exactType ? TypeReference.createExactTrusted(toType) : TypeReference.createWithoutAssumptions(toType), nonNull || StampTool.isPointerNonNull(object.stamp(NodeView.DEFAULT))); ValueNode value = canonical(object, stamp, (GuardingNode) guard, null); if (value == null) { value = new PiNode(object, stamp, guard); } b.push(JavaKind.Object, b.append(value)); return true; } /** * A stamp expressing the property that is proved by the {@linkplain #getGuard() guard}, but not * more. * </p> * * For example, if the guard proves a property {@code x >= 0} on an {@code int} value, then the * {@link #piStamp()} should be {@link StampFactory#positiveInt()}. If the input value's stamp * is constrained, e.g., {@code [-100 - 100]}, then this pi's overall {@link #stamp(NodeView)} * will be {@code [0 - 100]}, computed as the join of the {@link #piStamp()} and the input's * stamp. */ public final Stamp piStamp() { return piStamp; } public void strengthenPiStamp(Stamp newPiStamp) { assert this.piStamp.join(newPiStamp).equals(newPiStamp) : "stamp can only improve"; this.piStamp = newPiStamp; } @Override public void generate(NodeLIRBuilderTool generator) { if (generator.hasOperand(object)) { generator.setResult(this, generator.operand(object)); } } @Override public boolean inferStamp() { return updateStamp(computeStamp()); } private Stamp computeStamp() { return piStamp.improveWith(object().stamp(NodeView.DEFAULT)); } @Override public void virtualize(VirtualizerTool tool) { ValueNode alias = tool.getAlias(object()); if (alias instanceof VirtualObjectNode) { VirtualObjectNode virtual = (VirtualObjectNode) alias; ResolvedJavaType type = StampTool.typeOrNull(this, tool.getMetaAccess()); if (type != null && type.isAssignableFrom(virtual.type())) { tool.replaceWithVirtual(virtual); } else { tool.getDebug().log(DebugContext.INFO_LEVEL, "could not virtualize Pi because of type mismatch: %s %s vs %s", this, type, virtual.type()); } } } public static ValueNode canonical(ValueNode object, Stamp piStamp, GuardingNode guard, ValueNode self) { /* * If canonicalization is not explicitly triggered, we need to be conservative and assume * that the graph is still building up and some usages/inputs of/to nodes are still missing. */ return canonical(object, piStamp, guard, self, false); } public static ValueNode canonical(ValueNode object, Stamp piStamp, GuardingNode guard, ValueNode self, boolean allUsagesAvailable) { return canonical(object, piStamp, guard, self, allUsagesAvailable, true); } @SuppressFBWarnings(value = {"NP"}, justification = "We null check it before") public static ValueNode canonical(ValueNode object, Stamp piStamp, GuardingNode guard, ValueNode self, boolean allUsagesAvailable, boolean processUsage) { GraalError.guarantee(piStamp != null && object != null, "Invariant piStamp=%s object=%s guard=%s self=%s", piStamp, object, guard, self); // Use most up to date stamp. Stamp computedStamp = piStamp.improveWith(object.stamp(NodeView.DEFAULT)); // The pi node does not give any additional information => skip it. if (computedStamp.equals(object.stamp(NodeView.DEFAULT))) { return object; } /* * Extracts a constant node if (1) this pi node's stamp is a non-null pointer stamp, (2) * 'object' is phi node that has only the same constant node and else just null constants as * inputs, and (3) if the constant's stamp equals this pi node's stamp. * * @formatter:off * ... * | * Merge * | * | C(object) null null C(object) (...) * | | | | | | * | | | | | | * | |-------|-----+-----|-------| * | | * |----------------- phi * | * piWithNonNullStamp * | * ... * @formatter:on * * Another important condition is that the phi node already has all inputs. During graph * decoding, it may happen that inputs are added later for loop phis. Therefore, either * 'allUsagesAvailable' is given or the phi node is not a loop phi. * * This canonicalization case has some overlap with other optimizations. In particular, * aggressive path duplication may get to a very similar result. Also, 'IfNode.splitIfAtPhi' * does a similar optimization but with different limitations. This should be considered * when touching them. One advantage of this canonicalization is that it happens immediately * when creating PiNodes. */ if (StampFactory.objectNonNull().equals(piStamp) && object instanceof PhiNode phiNode && (allUsagesAvailable || !phiNode.isLoopPhi())) { ValueNode constantValue = null; for (ValueNode phiValue : phiNode.values()) { if (constantValue == null && phiValue.isConstant() && !phiValue.isNullConstant() && checkPhiValueStamp(piStamp, computedStamp, phiValue.stamp(NodeView.DEFAULT))) { constantValue = phiValue; } else if (!phiValue.isNullConstant() && (constantValue == null || !isSameConstant(constantValue, phiValue))) { // reset value to indicate that condition is violated constantValue = null; break; } } if (constantValue != null) { assert constantValue.isConstant() && !constantValue.isNullConstant() && checkPhiValueStamp(piStamp, computedStamp, constantValue.stamp(NodeView.DEFAULT)) : Assertions.errorMessageContext("pi", self, "phi", phiNode, "constant", constantValue); return constantValue; } } if (guard == null) { // Try to merge the pi node with a load node. if (object instanceof ReadNode && !object.hasMoreThanOneUsage()) { ReadNode readNode = (ReadNode) object; readNode.setStamp(readNode.stamp(NodeView.DEFAULT).improveWith(piStamp)); return readNode; } } else { if (processUsage && self instanceof PiNode selfPi) { for (Node n : guard.asNode().usages()) { if (n instanceof PiNode && n != self) { PiNode otherPi = (PiNode) n; ValueNode canonByOtherPi = tryImproveWithOtherPi(selfPi, otherPi); if (canonByOtherPi != null) { return canonByOtherPi; } } } } } return null; } /** * Canonicalizes a {@link PiNode} by comparing it with another {@link PiNode} based on guards, * objects, and stamps. Returns a replacement node if simplification or precision improvement is * possible. */ public static ValueNode tryImproveWithOtherPi(PiNode p1, PiNode p2) { GuardingNode guard = p1.guard; if (p2.guard != guard) { // though p1 and p2 use guard they do it on different edges, one as value the other as // guard (or vice versa) return null; } if (p2.object() == p1 || p2.object() == p1.object) { // Check if other pi's stamp is more precise Stamp joinedPiStamp = p1.piStamp.improveWith(p2.piStamp()); if (joinedPiStamp.equals(p1.piStamp)) { // Stamp did not get better, nothing to do. } else if (p2.object() == p1.object && joinedPiStamp.equals(p2.piStamp())) { // We can replace p1 with the other pi. return p2; } else if (p1.hasExactlyOneUsage() && p2.object == p1) { if (joinedPiStamp.equals(p2.piStamp)) { return p1.object; } } } return null; } /** * Pi-phi canonicalization is only allowed if the stamp of the phi: (1) is an object stamp * (because PiNodes on primitive values are flaky), (2) the computed stamp is equal to the phi * value's stamp, and (3) the stamp of the PiNode does not add any information. */ private static boolean checkPhiValueStamp(Stamp piStamp, Stamp computedStamp, Stamp phiValueStamp) { return phiValueStamp.isObjectStamp() && computedStamp.equals(phiValueStamp) && piStamp.join(phiValueStamp).equals(phiValueStamp); } private static boolean isSameConstant(ValueNode referenceValue, ValueNode phiValue) { assert referenceValue.isConstant() && !referenceValue.isNullConstant() : "reference value must be constant but not the null constant"; assert referenceValue.asConstant() != null : "constant must not be null"; return phiValue.isConstant() && referenceValue.asConstant().equals(phiValue.asConstant()); } @Override public Node canonical(CanonicalizerTool tool) { // usages run during canonicalization final boolean processUsages = false; Node value = canonical(object(), piStamp(), getGuard(), this, tool.allUsagesAvailable(), processUsages); if (value != null) { return value; } if (tool.allUsagesAvailable()) { for (Node usage : usages()) { if (!(usage instanceof VirtualState)) { return this; } } // Only state usages: for them a more precise stamp does not matter. return object; } return this; } /** * Perform Pi canonicalizations on any PiNodes anchored at {@code guard} in an attempt to * eliminate all of them. This purely done to enable earlier elimination of the user of these * PiNodes. */ public static void tryEvacuate(SimplifierTool tool, GuardingNode guard) { tryEvacuate(tool, guard, true); } private static void tryEvacuate(SimplifierTool tool, GuardingNode guard, boolean recurse) { ValueNode guardNode = guard.asNode(); if (guardNode.hasNoUsages()) { return; } List<PiNode> pis = guardNode.usages().filter(PiNode.class).snapshot(); for (PiNode pi : pis) { if (!pi.isAlive()) { continue; } if (pi.hasNoUsages()) { pi.safeDelete(); continue; } /* * RECURSE CALL * * If there are PiNodes still anchored at this guard then either they must simplify away * because they are no longer necessary or this node must be replaced with a * ValueAnchorNode because the type injected by the PiNode is only true at this point in * the control flow. */ if (recurse && pi.getOriginalNode() instanceof PiNode) { // It's not uncommon for one extra level of PiNode to inhibit removal of // this PiNode so try to simplify the input first. GuardingNode otherGuard = ((PiNode) pi.getOriginalNode()).guard; if (otherGuard != null) { tryEvacuate(tool, otherGuard, false); } } /* * A note on the RECURSE CALL above: When we have pis with input pis on the same guard * (which should actually be combined) it can be that the recurse call (processing the * same pis again) already deletes this node (very special stamp setups necessary). * Thus, it can be that pi is dead at this point already, so we have to check for this * again. */ if (!pi.isAlive()) { continue; } Node canonical = pi.canonical(tool); if (canonical != pi) { if (!canonical.isAlive()) { canonical = guardNode.graph().addOrUniqueWithInputs(canonical); } pi.replaceAtUsages(canonical); pi.safeDelete(); } } } @Override public ValueNode getOriginalNode() { return object; } public void setOriginalNode(ValueNode newNode) { this.updateUsages(object, newNode); this.object = newNode; assert piStamp.isCompatible(object.stamp(NodeView.DEFAULT)) : "New object stamp not compatible to piStamp"; } /** * Changes the stamp of an object inside a snippet to be the stamp of the node replaced by the * snippet. */ @NodeIntrinsic(PiNode.Placeholder.class) public static native Object piCastToSnippetReplaceeStamp(Object object); /** * Changes the stamp of a primitive value and ensures the newly stamped value is positive and * does not float above a given guard. * * @param value an arbitrary {@code int} value * @param guard a node proving that {@code value >= 0} holds at some point in the graph * * @return the {@code value} with its stamp clamped to exclude negative values, guarded by * {@code guard} */ public static int piCastPositive(int value, GuardingNode guard) { return intrinsified(value, guard, IntrinsifyOp.POSITIVE_INT); } public static int piCastNonZero(int value, GuardingNode guard) { return intrinsified(value, guard, IntrinsifyOp.INT_NON_ZERO); } public static long piCastNonZero(long value, GuardingNode guard) { return intrinsified(value, guard, IntrinsifyOp.LONG_NON_ZERO); } @NodeIntrinsic private static native int intrinsified(int value, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); @NodeIntrinsic private static native long intrinsified(long value, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); /** * Changes the stamp of an object and ensures the newly stamped value is non-null and does not * float above a given guard. */ public static Object piCastNonNull(Object object, GuardingNode guard) { return intrinsified(object, guard, IntrinsifyOp.NON_NULL); } @NodeIntrinsic private static native Object intrinsified(Object object, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); /** * Changes the stamp of an object and ensures the newly stamped value is non-null and does not * float above a given guard. */ public static Class<?> piCastNonNullClass(Class<?> type, GuardingNode guard) { return intrinsified(type, guard, IntrinsifyOp.NON_NULL); } public static float piCastNonNanFloat(float input, GuardingNode guard) { return intrinsified(input, guard, IntrinsifyOp.FLOAT_NON_NAN); } @NodeIntrinsic private static native float intrinsified(float input, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); public static double piCastNonNanDouble(double input, GuardingNode guard) { return intrinsified(input, guard, IntrinsifyOp.DOUBLE_NON_NAN); } @NodeIntrinsic private static native double intrinsified(double input, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); @NodeIntrinsic private static native Class<?> intrinsified(Class<?> object, GuardingNode guard, @ConstantNodeParameter IntrinsifyOp intrinsifyOp); @NodeIntrinsic public static native Object piCast(Object object, @ConstantNodeParameter ResolvedJavaType toType, @ConstantNodeParameter boolean exactType, @ConstantNodeParameter boolean nonNull, GuardingNode guard); @NodeIntrinsic public static native Object piCast(Object object, @ConstantNodeParameter Class<?> toType, @ConstantNodeParameter boolean exactType, @ConstantNodeParameter boolean nonNull, GuardingNode guard); /** * A placeholder node in a snippet that will be replaced with a {@link PiNode} when the snippet * is instantiated. */ @NodeInfo(cycles = CYCLES_0, size = SIZE_0) public static class Placeholder extends FloatingGuardedNode { public static final NodeClass<Placeholder> TYPE = NodeClass.create(Placeholder.class); @Input ValueNode object; public ValueNode object() { return object; } protected Placeholder(NodeClass<? extends Placeholder> c, ValueNode object) { super(c, PlaceholderStamp.SINGLETON, null); this.object = object; } public Placeholder(ValueNode object) { this(TYPE, object); } /** * Replaces this node with a {@link PiNode} during snippet instantiation. * * @param snippetReplaceeStamp the stamp of the node being replace by the snippet */ public void makeReplacement(Stamp snippetReplaceeStamp) { ValueNode value = graph().addOrUnique(PiNode.create(object(), snippetReplaceeStamp, null)); replaceAndDelete(value); } } /** * A stamp for {@link Placeholder} nodes which are only used in snippets. It is replaced by an * actual stamp when the snippet is instantiated. */ public static final class PlaceholderStamp extends ObjectStamp { private static final PlaceholderStamp SINGLETON = new PlaceholderStamp(); public static PlaceholderStamp singleton() { return SINGLETON; } private PlaceholderStamp() { super(null, false, false, false, false); } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "PlaceholderStamp"; } } /** * Maximum number of usage iterations per guard for * {@link PiNode#guardTrySkipPi(GuardingNode, LogicNode, boolean, NodeView)}. */ private static final int MAX_PI_USAGE_ITERATIONS = 8; /** * Optimize a (Fixed)Guard-condition-pi pattern as a whole: note that this is different than * conditional elimination because here we detect exhaustive patterns and optimize them as a * whole. This is hard to express in CE as we optimize both a pi and its condition in one go. * There is no dedicated optimization phase in graal that does this, therefore we build on * simplification as a more non-local transformation. * * We are looking for the following pattern * * <pre> * inputPiObject * | * inputPi----------- * | | * | | * usagePiCondition | * | | * (fixed) guard | * | | * usagePi----------- * </pre> * * and we optimize the condition and the pi together to use inputPi's input if inputPi does not * contribute any knowledge to usagePi. This means that inputPi is totally skipped. If both * inputPi and usagePi ultimately work on the same input (un-pi-ed) then later conditional * elimination can cleanup inputPi's guard if applicable. * * The resulting IR pattern will look like this: * * <pre> * inputPiObject------ * | | * | | * resultPiCondition | * | | * (fixed) guard | * | | * resultPi----------- * </pre> * * Note: this optimization does not work for subtypes of PiNode like {@link DynamicPiNode} as * their stamps are not yet known. * * A source code pattern illustrating the optimization can be found below * * <pre> * class A { * } * * class B { * } * * void foo(Object o) { * A bar = (A) o; * B baz = (B) bar; * use(b); * } * </pre> * * For the user of {@code baz} its not relevant to go over the first cast of {@code o} to * {@code A} since the condition of the second cast ({@code bar instanceof B}) already proves a * more concrete type than the first condition. We can skip the first cast of {@code o} to * {@code A} and later {@link ConditionalEliminationPhase} may be able to fully remove the first * condition. * * Note on conditional elimination and guard pi skipping: this optimization of skipping PIs DOES * NOT delete any guard nodes. So even if we skip pi nodes we are never removing guards. We are * only skipping pis if a later condition proves more knowledge than an earlier one. Conditional * elimination is the only phase that can prove that an earlier guard can be deleted because of * a later one. */ public static boolean guardTrySkipPi(GuardingNode guard, LogicNode condition, boolean negated, NodeView nodeView) { if (!(guard instanceof FixedGuardNode || guard instanceof GuardNode || guard instanceof BeginNode)) { /* * Unknown guard node: do not attempt to perform this transformation. */ return false; } final LogicNode usagePiCondition = condition; if (usagePiCondition.inputs().filter(PiNode.class).isEmpty()) { return false; } int iterations = 0; boolean progress = true; int pisSkipped = 0; outer: while (progress && iterations++ < MAX_PI_USAGE_ITERATIONS) { progress = false; // look for the pattern from the javadoc for (PiNode usagePi : piUsageSnapshot(guard)) { /* * Restrict this optimization to regular pi nodes only - sub classes of pi nodes * implement delayed pi stamp computation or other optimizations and should thus not * be skipped. */ if (!usagePi.isRegularPi()) { continue; } final ValueNode usagePiObject = usagePi.object(); final boolean usagePiObjectRegularPi = usagePiObject instanceof PiNode inputPi && inputPi.isRegularPi(); if (!usagePiObjectRegularPi) { continue; } // ensure usagePiObject is also used in the usagePiCondition if (!usagePiCondition.inputs().contains(usagePiObject)) { continue; } final Stamp usagePiPiStamp = usagePi.piStamp(); final PiNode inputPi = (PiNode) usagePiObject; /* * Ensure that the pi actually "belongs" to this guard in the sense that the * succeeding stamp for the guard is actually the pi stamp. */ Stamp succeedingStamp = null; if (usagePiCondition instanceof UnaryOpLogicNode uol) { succeedingStamp = uol.getSucceedingStampForValue(negated); } else if (usagePiCondition instanceof BinaryOpLogicNode bol) { if (bol.getX() == inputPi) { succeedingStamp = bol.getSucceedingStampForX(negated, bol.getX().stamp(nodeView), bol.getY().stamp(nodeView).unrestricted()); } else if (bol.getY() == inputPi) { succeedingStamp = bol.getSucceedingStampForY(negated, bol.getX().stamp(nodeView).unrestricted(), bol.getY().stamp(nodeView)); } } final boolean piProvenByCondition = succeedingStamp != null && usagePiPiStamp.equals(succeedingStamp); if (!piProvenByCondition) { continue; } /* * We want to find out if the inputPi can be skipped because usagePi's guard and pi * stamp prove enough knowledge to actually skip inputPi completely. This can be * relevant for complex type check patterns and interconnected pis: conditional * elimination cannot enumerate all values thus we try to free up local patterns * early by skipping unnecessary pis. */ final Stamp inputPiPiStamp = inputPi.piStamp(); final Stamp inputPiObjectStamp = inputPi.object().stamp(nodeView); /* * Determine if the stamp from inputPiObject & usagePi.piStamp is equally strong * than the usagePi.piStamp, then we can build a new pi that skips the inputPi. */ final Stamp resultStampWithInputPiObjectOnly = usagePiPiStamp.improveWith(inputPiObjectStamp); /* * The final pi will skip inputPi completely, thus inputPi.piStamp MUST NOT * contribute ANY additional stamp information, i.e., * resultStampWithInputPiObjectOnly cannot become any more precise through it. */ final boolean resultPiEquallyStrongWithoutInputPiPiStamp = resultStampWithInputPiObjectOnly.tryImproveWith(inputPiPiStamp) == null; if (resultPiEquallyStrongWithoutInputPiPiStamp) { // The input pi's object stamp was strong enough so we can skip the input pi. final ValueNode resultPi = usagePiCondition.graph().addOrUnique(PiNode.create(inputPi.object(), usagePiPiStamp, usagePi.getGuard().asNode())); final LogicNode resultPiCondition = (LogicNode) usagePiCondition.copyWithInputs(true); resultPiCondition.replaceAllInputs(usagePiObject, inputPi.object()); if (guard.asNode() instanceof FixedGuardNode fg) { fg.setCondition(resultPiCondition, negated); } else if (guard.asNode() instanceof GuardNode floatingGuard) { floatingGuard.setCondition(resultPiCondition, negated); } else if (guard.asNode() instanceof BeginNode) { ((IfNode) guard.asNode().predecessor()).setCondition(resultPiCondition); } else { GraalError.shouldNotReachHere("Unknown guard " + guard); } usagePi.replaceAndDelete(resultPi); progress = true; pisSkipped++; continue outer; } } } return pisSkipped > 0; } private boolean isRegularPi() { return getClass() == PiNode.class; } private static Iterable<PiNode> piUsageSnapshot(GuardingNode guard) { return guard.asNode().usages().filter(PiNode.class).snapshot(); } }
googleads/google-ads-java
35,620
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/ListPlannableLocationsResponse.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 list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.ListPlannableLocationsResponse} */ public final class ListPlannableLocationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.ListPlannableLocationsResponse) ListPlannableLocationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPlannableLocationsResponse.newBuilder() to construct. private ListPlannableLocationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPlannableLocationsResponse() { plannableLocations_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListPlannableLocationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ListPlannableLocationsResponse_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_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.Builder.class); } public static final int PLANNABLE_LOCATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v19.services.PlannableLocation> plannableLocations_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v19.services.PlannableLocation> getPlannableLocationsList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v19.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public int getPlannableLocationsCount() { return plannableLocations_.size(); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.PlannableLocation getPlannableLocations(int index) { return plannableLocations_.get(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { return plannableLocations_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < plannableLocations_.size(); i++) { output.writeMessage(1, plannableLocations_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < plannableLocations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, plannableLocations_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v19.services.ListPlannableLocationsResponse)) { return super.equals(obj); } com.google.ads.googleads.v19.services.ListPlannableLocationsResponse other = (com.google.ads.googleads.v19.services.ListPlannableLocationsResponse) obj; if (!getPlannableLocationsList() .equals(other.getPlannableLocationsList())) 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 (getPlannableLocationsCount() > 0) { hash = (37 * hash) + PLANNABLE_LOCATIONS_FIELD_NUMBER; hash = (53 * hash) + getPlannableLocationsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.services.ListPlannableLocationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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 list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.ListPlannableLocationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.ListPlannableLocationsResponse) com.google.ads.googleads.v19.services.ListPlannableLocationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v19_services_ListPlannableLocationsResponse_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_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.Builder.class); } // Construct using com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); } else { plannableLocations_ = null; plannableLocationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); 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_ListPlannableLocationsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.ListPlannableLocationsResponse build() { com.google.ads.googleads.v19.services.ListPlannableLocationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.ListPlannableLocationsResponse buildPartial() { com.google.ads.googleads.v19.services.ListPlannableLocationsResponse result = new com.google.ads.googleads.v19.services.ListPlannableLocationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v19.services.ListPlannableLocationsResponse result) { if (plannableLocationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = java.util.Collections.unmodifiableList(plannableLocations_); bitField0_ = (bitField0_ & ~0x00000001); } result.plannableLocations_ = plannableLocations_; } else { result.plannableLocations_ = plannableLocationsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v19.services.ListPlannableLocationsResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v19.services.ListPlannableLocationsResponse) { return mergeFrom((com.google.ads.googleads.v19.services.ListPlannableLocationsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.ListPlannableLocationsResponse other) { if (other == com.google.ads.googleads.v19.services.ListPlannableLocationsResponse.getDefaultInstance()) return this; if (plannableLocationsBuilder_ == null) { if (!other.plannableLocations_.isEmpty()) { if (plannableLocations_.isEmpty()) { plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePlannableLocationsIsMutable(); plannableLocations_.addAll(other.plannableLocations_); } onChanged(); } } else { if (!other.plannableLocations_.isEmpty()) { if (plannableLocationsBuilder_.isEmpty()) { plannableLocationsBuilder_.dispose(); plannableLocationsBuilder_ = null; plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); plannableLocationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPlannableLocationsFieldBuilder() : null; } else { plannableLocationsBuilder_.addAllMessages(other.plannableLocations_); } } } 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.ads.googleads.v19.services.PlannableLocation m = input.readMessage( com.google.ads.googleads.v19.services.PlannableLocation.parser(), extensionRegistry); if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(m); } else { plannableLocationsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v19.services.PlannableLocation> plannableLocations_ = java.util.Collections.emptyList(); private void ensurePlannableLocationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = new java.util.ArrayList<com.google.ads.googleads.v19.services.PlannableLocation>(plannableLocations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.PlannableLocation, com.google.ads.googleads.v19.services.PlannableLocation.Builder, com.google.ads.googleads.v19.services.PlannableLocationOrBuilder> plannableLocationsBuilder_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v19.services.PlannableLocation> getPlannableLocationsList() { if (plannableLocationsBuilder_ == null) { return java.util.Collections.unmodifiableList(plannableLocations_); } else { return plannableLocationsBuilder_.getMessageList(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public int getPlannableLocationsCount() { if (plannableLocationsBuilder_ == null) { return plannableLocations_.size(); } else { return plannableLocationsBuilder_.getCount(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v19.services.PlannableLocation getPlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessage(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v19.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, value); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v19.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations(com.google.ads.googleads.v19.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(value); onChanged(); } else { plannableLocationsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v19.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, value); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( com.google.ads.googleads.v19.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v19.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addAllPlannableLocations( java.lang.Iterable<? extends com.google.ads.googleads.v19.services.PlannableLocation> values) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, plannableLocations_); onChanged(); } else { plannableLocationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder clearPlannableLocations() { if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { plannableLocationsBuilder_.clear(); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public Builder removePlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.remove(index); onChanged(); } else { plannableLocationsBuilder_.remove(index); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v19.services.PlannableLocation.Builder getPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().getBuilder(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v19.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v19.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { if (plannableLocationsBuilder_ != null) { return plannableLocationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(plannableLocations_); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v19.services.PlannableLocation.Builder addPlannableLocationsBuilder() { return getPlannableLocationsFieldBuilder().addBuilder( com.google.ads.googleads.v19.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v19.services.PlannableLocation.Builder addPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v19.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v19.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v19.services.PlannableLocation.Builder> getPlannableLocationsBuilderList() { return getPlannableLocationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.PlannableLocation, com.google.ads.googleads.v19.services.PlannableLocation.Builder, com.google.ads.googleads.v19.services.PlannableLocationOrBuilder> getPlannableLocationsFieldBuilder() { if (plannableLocationsBuilder_ == null) { plannableLocationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.PlannableLocation, com.google.ads.googleads.v19.services.PlannableLocation.Builder, com.google.ads.googleads.v19.services.PlannableLocationOrBuilder>( plannableLocations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); plannableLocations_ = null; } return plannableLocationsBuilder_; } @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.ListPlannableLocationsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.ListPlannableLocationsResponse) private static final com.google.ads.googleads.v19.services.ListPlannableLocationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.ListPlannableLocationsResponse(); } public static com.google.ads.googleads.v19.services.ListPlannableLocationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPlannableLocationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListPlannableLocationsResponse>() { @java.lang.Override public ListPlannableLocationsResponse 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<ListPlannableLocationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPlannableLocationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,620
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/ListPlannableLocationsResponse.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 list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.ListPlannableLocationsResponse} */ public final class ListPlannableLocationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.ListPlannableLocationsResponse) ListPlannableLocationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPlannableLocationsResponse.newBuilder() to construct. private ListPlannableLocationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPlannableLocationsResponse() { plannableLocations_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListPlannableLocationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ListPlannableLocationsResponse_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_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.Builder.class); } public static final int PLANNABLE_LOCATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v20.services.PlannableLocation> plannableLocations_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v20.services.PlannableLocation> getPlannableLocationsList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v20.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public int getPlannableLocationsCount() { return plannableLocations_.size(); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.PlannableLocation getPlannableLocations(int index) { return plannableLocations_.get(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { return plannableLocations_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < plannableLocations_.size(); i++) { output.writeMessage(1, plannableLocations_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < plannableLocations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, plannableLocations_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v20.services.ListPlannableLocationsResponse)) { return super.equals(obj); } com.google.ads.googleads.v20.services.ListPlannableLocationsResponse other = (com.google.ads.googleads.v20.services.ListPlannableLocationsResponse) obj; if (!getPlannableLocationsList() .equals(other.getPlannableLocationsList())) 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 (getPlannableLocationsCount() > 0) { hash = (37 * hash) + PLANNABLE_LOCATIONS_FIELD_NUMBER; hash = (53 * hash) + getPlannableLocationsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.services.ListPlannableLocationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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 list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.ListPlannableLocationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.ListPlannableLocationsResponse) com.google.ads.googleads.v20.services.ListPlannableLocationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v20_services_ListPlannableLocationsResponse_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_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.Builder.class); } // Construct using com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); } else { plannableLocations_ = null; plannableLocationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); 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_ListPlannableLocationsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.ListPlannableLocationsResponse build() { com.google.ads.googleads.v20.services.ListPlannableLocationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.ListPlannableLocationsResponse buildPartial() { com.google.ads.googleads.v20.services.ListPlannableLocationsResponse result = new com.google.ads.googleads.v20.services.ListPlannableLocationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v20.services.ListPlannableLocationsResponse result) { if (plannableLocationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = java.util.Collections.unmodifiableList(plannableLocations_); bitField0_ = (bitField0_ & ~0x00000001); } result.plannableLocations_ = plannableLocations_; } else { result.plannableLocations_ = plannableLocationsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v20.services.ListPlannableLocationsResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v20.services.ListPlannableLocationsResponse) { return mergeFrom((com.google.ads.googleads.v20.services.ListPlannableLocationsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.ListPlannableLocationsResponse other) { if (other == com.google.ads.googleads.v20.services.ListPlannableLocationsResponse.getDefaultInstance()) return this; if (plannableLocationsBuilder_ == null) { if (!other.plannableLocations_.isEmpty()) { if (plannableLocations_.isEmpty()) { plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePlannableLocationsIsMutable(); plannableLocations_.addAll(other.plannableLocations_); } onChanged(); } } else { if (!other.plannableLocations_.isEmpty()) { if (plannableLocationsBuilder_.isEmpty()) { plannableLocationsBuilder_.dispose(); plannableLocationsBuilder_ = null; plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); plannableLocationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPlannableLocationsFieldBuilder() : null; } else { plannableLocationsBuilder_.addAllMessages(other.plannableLocations_); } } } 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.ads.googleads.v20.services.PlannableLocation m = input.readMessage( com.google.ads.googleads.v20.services.PlannableLocation.parser(), extensionRegistry); if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(m); } else { plannableLocationsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v20.services.PlannableLocation> plannableLocations_ = java.util.Collections.emptyList(); private void ensurePlannableLocationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = new java.util.ArrayList<com.google.ads.googleads.v20.services.PlannableLocation>(plannableLocations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.PlannableLocation, com.google.ads.googleads.v20.services.PlannableLocation.Builder, com.google.ads.googleads.v20.services.PlannableLocationOrBuilder> plannableLocationsBuilder_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v20.services.PlannableLocation> getPlannableLocationsList() { if (plannableLocationsBuilder_ == null) { return java.util.Collections.unmodifiableList(plannableLocations_); } else { return plannableLocationsBuilder_.getMessageList(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public int getPlannableLocationsCount() { if (plannableLocationsBuilder_ == null) { return plannableLocations_.size(); } else { return plannableLocationsBuilder_.getCount(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v20.services.PlannableLocation getPlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessage(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v20.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, value); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v20.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations(com.google.ads.googleads.v20.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(value); onChanged(); } else { plannableLocationsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v20.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, value); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( com.google.ads.googleads.v20.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v20.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addAllPlannableLocations( java.lang.Iterable<? extends com.google.ads.googleads.v20.services.PlannableLocation> values) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, plannableLocations_); onChanged(); } else { plannableLocationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder clearPlannableLocations() { if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { plannableLocationsBuilder_.clear(); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public Builder removePlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.remove(index); onChanged(); } else { plannableLocationsBuilder_.remove(index); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v20.services.PlannableLocation.Builder getPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().getBuilder(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v20.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v20.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { if (plannableLocationsBuilder_ != null) { return plannableLocationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(plannableLocations_); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v20.services.PlannableLocation.Builder addPlannableLocationsBuilder() { return getPlannableLocationsFieldBuilder().addBuilder( com.google.ads.googleads.v20.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v20.services.PlannableLocation.Builder addPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v20.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v20.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v20.services.PlannableLocation.Builder> getPlannableLocationsBuilderList() { return getPlannableLocationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.PlannableLocation, com.google.ads.googleads.v20.services.PlannableLocation.Builder, com.google.ads.googleads.v20.services.PlannableLocationOrBuilder> getPlannableLocationsFieldBuilder() { if (plannableLocationsBuilder_ == null) { plannableLocationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.PlannableLocation, com.google.ads.googleads.v20.services.PlannableLocation.Builder, com.google.ads.googleads.v20.services.PlannableLocationOrBuilder>( plannableLocations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); plannableLocations_ = null; } return plannableLocationsBuilder_; } @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.ListPlannableLocationsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.ListPlannableLocationsResponse) private static final com.google.ads.googleads.v20.services.ListPlannableLocationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.ListPlannableLocationsResponse(); } public static com.google.ads.googleads.v20.services.ListPlannableLocationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPlannableLocationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListPlannableLocationsResponse>() { @java.lang.Override public ListPlannableLocationsResponse 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<ListPlannableLocationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPlannableLocationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
35,620
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/ListPlannableLocationsResponse.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/reach_plan_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * The list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.ListPlannableLocationsResponse} */ public final class ListPlannableLocationsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.ListPlannableLocationsResponse) ListPlannableLocationsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPlannableLocationsResponse.newBuilder() to construct. private ListPlannableLocationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPlannableLocationsResponse() { plannableLocations_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListPlannableLocationsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v21_services_ListPlannableLocationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v21_services_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.Builder.class); } public static final int PLANNABLE_LOCATIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v21.services.PlannableLocation> plannableLocations_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v21.services.PlannableLocation> getPlannableLocationsList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v21.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { return plannableLocations_; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public int getPlannableLocationsCount() { return plannableLocations_.size(); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.PlannableLocation getPlannableLocations(int index) { return plannableLocations_.get(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { return plannableLocations_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < plannableLocations_.size(); i++) { output.writeMessage(1, plannableLocations_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < plannableLocations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, plannableLocations_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v21.services.ListPlannableLocationsResponse)) { return super.equals(obj); } com.google.ads.googleads.v21.services.ListPlannableLocationsResponse other = (com.google.ads.googleads.v21.services.ListPlannableLocationsResponse) obj; if (!getPlannableLocationsList() .equals(other.getPlannableLocationsList())) 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 (getPlannableLocationsCount() > 0) { hash = (37 * hash) + PLANNABLE_LOCATIONS_FIELD_NUMBER; hash = (53 * hash) + getPlannableLocationsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.services.ListPlannableLocationsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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.ListPlannableLocationsResponse 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 list of plannable locations. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.ListPlannableLocationsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.ListPlannableLocationsResponse) com.google.ads.googleads.v21.services.ListPlannableLocationsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v21_services_ListPlannableLocationsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v21_services_ListPlannableLocationsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.class, com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.Builder.class); } // Construct using com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); } else { plannableLocations_ = null; plannableLocationsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.ReachPlanServiceProto.internal_static_google_ads_googleads_v21_services_ListPlannableLocationsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.ListPlannableLocationsResponse build() { com.google.ads.googleads.v21.services.ListPlannableLocationsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.ListPlannableLocationsResponse buildPartial() { com.google.ads.googleads.v21.services.ListPlannableLocationsResponse result = new com.google.ads.googleads.v21.services.ListPlannableLocationsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v21.services.ListPlannableLocationsResponse result) { if (plannableLocationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = java.util.Collections.unmodifiableList(plannableLocations_); bitField0_ = (bitField0_ & ~0x00000001); } result.plannableLocations_ = plannableLocations_; } else { result.plannableLocations_ = plannableLocationsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v21.services.ListPlannableLocationsResponse result) { int from_bitField0_ = bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v21.services.ListPlannableLocationsResponse) { return mergeFrom((com.google.ads.googleads.v21.services.ListPlannableLocationsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.ListPlannableLocationsResponse other) { if (other == com.google.ads.googleads.v21.services.ListPlannableLocationsResponse.getDefaultInstance()) return this; if (plannableLocationsBuilder_ == null) { if (!other.plannableLocations_.isEmpty()) { if (plannableLocations_.isEmpty()) { plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePlannableLocationsIsMutable(); plannableLocations_.addAll(other.plannableLocations_); } onChanged(); } } else { if (!other.plannableLocations_.isEmpty()) { if (plannableLocationsBuilder_.isEmpty()) { plannableLocationsBuilder_.dispose(); plannableLocationsBuilder_ = null; plannableLocations_ = other.plannableLocations_; bitField0_ = (bitField0_ & ~0x00000001); plannableLocationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPlannableLocationsFieldBuilder() : null; } else { plannableLocationsBuilder_.addAllMessages(other.plannableLocations_); } } } 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.ads.googleads.v21.services.PlannableLocation m = input.readMessage( com.google.ads.googleads.v21.services.PlannableLocation.parser(), extensionRegistry); if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(m); } else { plannableLocationsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v21.services.PlannableLocation> plannableLocations_ = java.util.Collections.emptyList(); private void ensurePlannableLocationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { plannableLocations_ = new java.util.ArrayList<com.google.ads.googleads.v21.services.PlannableLocation>(plannableLocations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.PlannableLocation, com.google.ads.googleads.v21.services.PlannableLocation.Builder, com.google.ads.googleads.v21.services.PlannableLocationOrBuilder> plannableLocationsBuilder_; /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v21.services.PlannableLocation> getPlannableLocationsList() { if (plannableLocationsBuilder_ == null) { return java.util.Collections.unmodifiableList(plannableLocations_); } else { return plannableLocationsBuilder_.getMessageList(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public int getPlannableLocationsCount() { if (plannableLocationsBuilder_ == null) { return plannableLocations_.size(); } else { return plannableLocationsBuilder_.getCount(); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v21.services.PlannableLocation getPlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessage(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v21.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, value); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder setPlannableLocations( int index, com.google.ads.googleads.v21.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.set(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations(com.google.ads.googleads.v21.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(value); onChanged(); } else { plannableLocationsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v21.services.PlannableLocation value) { if (plannableLocationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, value); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( com.google.ads.googleads.v21.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addPlannableLocations( int index, com.google.ads.googleads.v21.services.PlannableLocation.Builder builderForValue) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.add(index, builderForValue.build()); onChanged(); } else { plannableLocationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder addAllPlannableLocations( java.lang.Iterable<? extends com.google.ads.googleads.v21.services.PlannableLocation> values) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, plannableLocations_); onChanged(); } else { plannableLocationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder clearPlannableLocations() { if (plannableLocationsBuilder_ == null) { plannableLocations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { plannableLocationsBuilder_.clear(); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public Builder removePlannableLocations(int index) { if (plannableLocationsBuilder_ == null) { ensurePlannableLocationsIsMutable(); plannableLocations_.remove(index); onChanged(); } else { plannableLocationsBuilder_.remove(index); } return this; } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v21.services.PlannableLocation.Builder getPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().getBuilder(index); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v21.services.PlannableLocationOrBuilder getPlannableLocationsOrBuilder( int index) { if (plannableLocationsBuilder_ == null) { return plannableLocations_.get(index); } else { return plannableLocationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v21.services.PlannableLocationOrBuilder> getPlannableLocationsOrBuilderList() { if (plannableLocationsBuilder_ != null) { return plannableLocationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(plannableLocations_); } } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v21.services.PlannableLocation.Builder addPlannableLocationsBuilder() { return getPlannableLocationsFieldBuilder().addBuilder( com.google.ads.googleads.v21.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public com.google.ads.googleads.v21.services.PlannableLocation.Builder addPlannableLocationsBuilder( int index) { return getPlannableLocationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v21.services.PlannableLocation.getDefaultInstance()); } /** * <pre> * The list of locations available for planning. * See * https://developers.google.com/google-ads/api/reference/data/geotargets * for sample locations. * </pre> * * <code>repeated .google.ads.googleads.v21.services.PlannableLocation plannable_locations = 1;</code> */ public java.util.List<com.google.ads.googleads.v21.services.PlannableLocation.Builder> getPlannableLocationsBuilderList() { return getPlannableLocationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.PlannableLocation, com.google.ads.googleads.v21.services.PlannableLocation.Builder, com.google.ads.googleads.v21.services.PlannableLocationOrBuilder> getPlannableLocationsFieldBuilder() { if (plannableLocationsBuilder_ == null) { plannableLocationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.PlannableLocation, com.google.ads.googleads.v21.services.PlannableLocation.Builder, com.google.ads.googleads.v21.services.PlannableLocationOrBuilder>( plannableLocations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); plannableLocations_ = null; } return plannableLocationsBuilder_; } @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.ListPlannableLocationsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.ListPlannableLocationsResponse) private static final com.google.ads.googleads.v21.services.ListPlannableLocationsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.ListPlannableLocationsResponse(); } public static com.google.ads.googleads.v21.services.ListPlannableLocationsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPlannableLocationsResponse> PARSER = new com.google.protobuf.AbstractParser<ListPlannableLocationsResponse>() { @java.lang.Override public ListPlannableLocationsResponse 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<ListPlannableLocationsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPlannableLocationsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.ListPlannableLocationsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/incubator-tez
35,357
tez-dag/src/main/java/org/apache/tez/dag/app/RecoveryParser.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.tez.dag.app; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.tez.common.TezCommonUtils; import org.apache.tez.dag.api.TezConfiguration; import org.apache.tez.dag.app.dag.DAGState; import org.apache.tez.dag.app.dag.Task; import org.apache.tez.dag.app.dag.Vertex; import org.apache.tez.dag.app.dag.impl.DAGImpl; import org.apache.tez.dag.history.HistoryEvent; import org.apache.tez.dag.history.HistoryEventType; import org.apache.tez.dag.history.events.AMLaunchedEvent; import org.apache.tez.dag.history.events.AMStartedEvent; import org.apache.tez.dag.history.events.ContainerLaunchedEvent; import org.apache.tez.dag.history.events.ContainerStoppedEvent; import org.apache.tez.dag.history.events.DAGCommitStartedEvent; import org.apache.tez.dag.history.events.DAGFinishedEvent; import org.apache.tez.dag.history.events.DAGInitializedEvent; import org.apache.tez.dag.history.events.DAGStartedEvent; import org.apache.tez.dag.history.events.DAGSubmittedEvent; import org.apache.tez.dag.history.events.TaskAttemptFinishedEvent; import org.apache.tez.dag.history.events.TaskAttemptStartedEvent; import org.apache.tez.dag.history.events.TaskFinishedEvent; import org.apache.tez.dag.history.events.TaskStartedEvent; import org.apache.tez.dag.history.events.VertexCommitStartedEvent; import org.apache.tez.dag.history.events.VertexDataMovementEventsGeneratedEvent; import org.apache.tez.dag.history.events.VertexFinishedEvent; import org.apache.tez.dag.history.events.VertexGroupCommitFinishedEvent; import org.apache.tez.dag.history.events.VertexGroupCommitStartedEvent; import org.apache.tez.dag.history.events.VertexInitializedEvent; import org.apache.tez.dag.history.events.VertexParallelismUpdatedEvent; import org.apache.tez.dag.history.events.VertexStartedEvent; import org.apache.tez.dag.history.recovery.RecoveryService; import org.apache.tez.dag.records.TezDAGID; import org.apache.tez.dag.records.TezVertexID; import org.apache.tez.dag.recovery.records.RecoveryProtos; import org.apache.tez.dag.recovery.records.RecoveryProtos.SummaryEventProto; public class RecoveryParser { private static final Log LOG = LogFactory.getLog(RecoveryParser.class); private final DAGAppMaster dagAppMaster; private final FileSystem recoveryFS; private final Path recoveryDataDir; private final Path currentAttemptRecoveryDataDir; private final int recoveryBufferSize; private final int currentAttemptId; private static final String dataRecoveredFileFlag = "dataRecovered"; public RecoveryParser(DAGAppMaster dagAppMaster, FileSystem recoveryFS, Path recoveryDataDir, int currentAttemptId) throws IOException { this.dagAppMaster = dagAppMaster; this.recoveryFS = recoveryFS; this.recoveryDataDir = recoveryDataDir; this.currentAttemptId = currentAttemptId; this.currentAttemptRecoveryDataDir = TezCommonUtils.getAttemptRecoveryPath(recoveryDataDir, currentAttemptId); recoveryBufferSize = dagAppMaster.getConfig().getInt( TezConfiguration.DAG_RECOVERY_FILE_IO_BUFFER_SIZE, TezConfiguration.DAG_RECOVERY_FILE_IO_BUFFER_SIZE_DEFAULT); this.recoveryFS.mkdirs(currentAttemptRecoveryDataDir); } public static class RecoveredDAGData { public TezDAGID recoveredDagID = null; public DAGImpl recoveredDAG = null; public DAGState dagState = null; public boolean isCompleted = false; public boolean nonRecoverable = false; public String reason = null; public Map<String, LocalResource> cumulativeAdditionalResources = null; } private static void parseSummaryFile(FSDataInputStream inputStream) throws IOException { while (true) { RecoveryProtos.SummaryEventProto proto = RecoveryProtos.SummaryEventProto.parseDelimitedFrom(inputStream); if (proto == null) { LOG.info("Reached end of summary stream"); break; } LOG.info("[SUMMARY]" + " dagId=" + proto.getDagId() + ", timestamp=" + proto.getTimestamp() + ", event=" + HistoryEventType.values()[proto.getEventType()]); } } private static HistoryEvent getNextEvent(FSDataInputStream inputStream) throws IOException { int eventTypeOrdinal = -1; try { eventTypeOrdinal = inputStream.readInt(); } catch (EOFException eof) { return null; } if (eventTypeOrdinal < 0 || eventTypeOrdinal >= HistoryEventType.values().length) { // Corrupt data // reached end throw new IOException("Corrupt data found when trying to read next event type" + ", eventTypeOrdinal=" + eventTypeOrdinal); } HistoryEventType eventType = HistoryEventType.values()[eventTypeOrdinal]; HistoryEvent event; switch (eventType) { case AM_LAUNCHED: event = new AMLaunchedEvent(); break; case AM_STARTED: event = new AMStartedEvent(); break; case DAG_SUBMITTED: event = new DAGSubmittedEvent(); break; case DAG_INITIALIZED: event = new DAGInitializedEvent(); break; case DAG_STARTED: event = new DAGStartedEvent(); break; case DAG_COMMIT_STARTED: event = new DAGCommitStartedEvent(); break; case DAG_FINISHED: event = new DAGFinishedEvent(); break; case CONTAINER_LAUNCHED: event = new ContainerLaunchedEvent(); break; case CONTAINER_STOPPED: event = new ContainerStoppedEvent(); break; case VERTEX_INITIALIZED: event = new VertexInitializedEvent(); break; case VERTEX_STARTED: event = new VertexStartedEvent(); break; case VERTEX_PARALLELISM_UPDATED: event = new VertexParallelismUpdatedEvent(); break; case VERTEX_COMMIT_STARTED: event = new VertexCommitStartedEvent(); break; case VERTEX_GROUP_COMMIT_STARTED: event = new VertexGroupCommitStartedEvent(); break; case VERTEX_GROUP_COMMIT_FINISHED: event = new VertexGroupCommitFinishedEvent(); break; case VERTEX_FINISHED: event = new VertexFinishedEvent(); break; case TASK_STARTED: event = new TaskStartedEvent(); break; case TASK_FINISHED: event = new TaskFinishedEvent(); break; case TASK_ATTEMPT_STARTED: event = new TaskAttemptStartedEvent(); break; case TASK_ATTEMPT_FINISHED: event = new TaskAttemptFinishedEvent(); break; case VERTEX_DATA_MOVEMENT_EVENTS_GENERATED: event = new VertexDataMovementEventsGeneratedEvent(); break; default: throw new IOException("Invalid data found, unknown event type " + eventType); } if (LOG.isDebugEnabled()) { LOG.debug("Parsing event from input stream" + ", eventType=" + eventType); } try { event.fromProtoStream(inputStream); } catch (EOFException eof) { return null; } if (LOG.isDebugEnabled()) { LOG.debug("Parsed event from input stream" + ", eventType=" + eventType + ", event=" + event.toString()); } return event; } private static void parseDAGRecoveryFile(FSDataInputStream inputStream) throws IOException { while (true) { HistoryEvent historyEvent = getNextEvent(inputStream); if (historyEvent == null) { LOG.info("Reached end of stream"); break; } LOG.info("Parsed event from recovery stream" + ", eventType=" + historyEvent.getEventType() + ", event=" + historyEvent); } } public static void main(String argv[]) throws IOException { // TODO clean up with better usage and error handling Configuration conf = new Configuration(); String summaryPath = argv[0]; List<String> dagPaths = new ArrayList<String>(); if (argv.length > 1) { for (int i = 1; i < argv.length; ++i) { dagPaths.add(argv[i]); } } FileSystem fs = FileSystem.get(conf); LOG.info("Parsing Summary file " + summaryPath); parseSummaryFile(fs.open(new Path(summaryPath))); for (String dagPath : dagPaths) { LOG.info("Parsing DAG recovery file " + dagPath); parseDAGRecoveryFile(fs.open(new Path(dagPath))); } } private Path getSummaryPath(Path attemptRrecoveryDataDir) { return TezCommonUtils.getSummaryRecoveryPath(attemptRrecoveryDataDir); } private FSDataOutputStream getSummaryOutputStream(Path summaryPath) throws IOException { return recoveryFS.create(summaryPath, true, recoveryBufferSize); } private FSDataInputStream getSummaryStream(Path summaryPath) throws IOException { if (!recoveryFS.exists(summaryPath)) { return null; } return recoveryFS.open(summaryPath, recoveryBufferSize); } private Path getDAGRecoveryFilePath(Path recoveryDataDir, TezDAGID dagID) { return new Path(recoveryDataDir, dagID.toString() + TezConfiguration.DAG_RECOVERY_RECOVER_FILE_SUFFIX); } private FSDataInputStream getDAGRecoveryStream(Path recoveryDataDir, TezDAGID dagID) throws IOException { Path dagRecoveryPath = getDAGRecoveryFilePath(recoveryDataDir, dagID); if (!recoveryFS.exists(dagRecoveryPath)) { return null; } return recoveryFS.open(dagRecoveryPath, recoveryBufferSize); } private FSDataOutputStream getDAGRecoveryOutputStream(Path recoveryDataDir, TezDAGID dagID) throws IOException { Path dagRecoveryPath = new Path(recoveryDataDir, dagID.toString() + TezConfiguration.DAG_RECOVERY_RECOVER_FILE_SUFFIX); return recoveryFS.create(dagRecoveryPath, true, recoveryBufferSize); } private DAGSummaryData getLastCompletedOrInProgressDAG( Map<TezDAGID, DAGSummaryData> dagSummaryDataMap) { DAGSummaryData inProgressDAG = null; DAGSummaryData lastCompletedDAG = null; for (Map.Entry<TezDAGID, DAGSummaryData> entry : dagSummaryDataMap.entrySet()) { if (!entry.getValue().completed) { if (inProgressDAG != null) { throw new RuntimeException("Multiple in progress DAGs seen" + ", dagId=" + inProgressDAG.dagId + ", dagId=" + entry.getKey()); } inProgressDAG = entry.getValue(); } else { lastCompletedDAG = entry.getValue(); } } if (inProgressDAG == null) { return lastCompletedDAG; } return inProgressDAG; } private Path getPreviousAttemptRecoveryDataDir() throws IOException { LOG.info("Looking for the correct attempt directory to recover from"); int foundPreviousAttempt = -1; for (int i = currentAttemptId - 1; i > 0; --i) { Path attemptPath = TezCommonUtils.getAttemptRecoveryPath(recoveryDataDir, i); LOG.info("Looking at attempt directory, path=" + attemptPath); Path fatalErrorOccurred = new Path(attemptPath, RecoveryService.RECOVERY_FATAL_OCCURRED_DIR); if (recoveryFS.exists(fatalErrorOccurred)) { throw new IOException("Found that a fatal error occurred in" + " recovery during previous attempt, foundFile=" + fatalErrorOccurred.toString()); } Path dataRecoveredFile = new Path(attemptPath, dataRecoveredFileFlag); try { if (recoveryFS.exists(dataRecoveredFile)) { LOG.info("Found data recovered file in attempt directory" + ", dataRecoveredFile=" + dataRecoveredFile + ", path=" + attemptPath); foundPreviousAttempt = i; break; } LOG.info("Skipping attempt directory as data recovered file does not exist" + ", dataRecoveredFile=" + dataRecoveredFile + ", path=" + attemptPath); } catch (IOException e) { LOG.warn("Exception when checking previous attempt dir for " + dataRecoveredFile.toString(), e); } } if (foundPreviousAttempt == -1) { // Look for oldest summary file and use that LOG.info("Did not find any attempt dir that had data recovered file." + " Looking for oldest summary file"); for (int i = 1; i < currentAttemptId; ++i) { Path attemptPath = TezCommonUtils.getAttemptRecoveryPath(recoveryDataDir, i); Path summaryPath = getSummaryPath(attemptPath); if (recoveryFS.exists(summaryPath)) { LOG.info("Found summary file in attempt directory" + ", summaryFile=" + summaryPath + ", path=" + attemptPath); foundPreviousAttempt = i; break; } LOG.info("Skipping attempt directory as no summary file found" + ", summaryFile=" + summaryPath + ", path=" + attemptPath); } } if (foundPreviousAttempt == -1) { LOG.info("Falling back to first attempt as no other recovered attempts" + " found"); foundPreviousAttempt = 1; } return TezCommonUtils.getAttemptRecoveryPath(recoveryDataDir, foundPreviousAttempt); } private static class DAGSummaryData { final TezDAGID dagId; boolean completed = false; boolean dagCommitCompleted = true; DAGState dagState; Map<TezVertexID, Boolean> vertexCommitStatus = new HashMap<TezVertexID, Boolean>(); Map<String, Boolean> vertexGroupCommitStatus = new HashMap<String, Boolean>(); List<HistoryEvent> bufferedSummaryEvents = new ArrayList<HistoryEvent>(); DAGSummaryData(TezDAGID dagId) { this.dagId = dagId; } void handleSummaryEvent(SummaryEventProto proto) throws IOException { HistoryEventType eventType = HistoryEventType.values()[proto.getEventType()]; switch (eventType) { case DAG_SUBMITTED: completed = false; break; case DAG_FINISHED: completed = true; dagCommitCompleted = true; DAGFinishedEvent dagFinishedEvent = new DAGFinishedEvent(); dagFinishedEvent.fromSummaryProtoStream(proto); dagState = dagFinishedEvent.getState(); break; case DAG_COMMIT_STARTED: dagCommitCompleted = false; break; case VERTEX_COMMIT_STARTED: VertexCommitStartedEvent vertexCommitStartedEvent = new VertexCommitStartedEvent(); vertexCommitStartedEvent.fromSummaryProtoStream(proto); vertexCommitStatus.put( vertexCommitStartedEvent.getVertexID(), false); break; case VERTEX_FINISHED: VertexFinishedEvent vertexFinishedEvent = new VertexFinishedEvent(); vertexFinishedEvent.fromSummaryProtoStream(proto); if (vertexCommitStatus.containsKey(vertexFinishedEvent.getVertexID())) { vertexCommitStatus.put( vertexFinishedEvent.getVertexID(), true); bufferedSummaryEvents.add(vertexFinishedEvent); } break; case VERTEX_GROUP_COMMIT_STARTED: VertexGroupCommitStartedEvent vertexGroupCommitStartedEvent = new VertexGroupCommitStartedEvent(); vertexGroupCommitStartedEvent.fromSummaryProtoStream(proto); bufferedSummaryEvents.add(vertexGroupCommitStartedEvent); vertexGroupCommitStatus.put( vertexGroupCommitStartedEvent.getVertexGroupName(), false); break; case VERTEX_GROUP_COMMIT_FINISHED: VertexGroupCommitFinishedEvent vertexGroupCommitFinishedEvent = new VertexGroupCommitFinishedEvent(); vertexGroupCommitFinishedEvent.fromSummaryProtoStream(proto); bufferedSummaryEvents.add(vertexGroupCommitFinishedEvent); vertexGroupCommitStatus.put( vertexGroupCommitFinishedEvent.getVertexGroupName(), true); break; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("dagId=").append(dagId); sb.append(", dagCompleted=").append(completed); if (!vertexCommitStatus.isEmpty()) { sb.append(", vertexCommitStatuses=["); for (Entry<TezVertexID, Boolean> entry : vertexCommitStatus.entrySet()) { sb.append("{ vertexId=").append(entry.getKey()) .append(", committed=").append(entry.getValue()).append("}, "); } sb.append("]"); } if (!vertexGroupCommitStatus.isEmpty()) { sb.append(", vertexGroupCommitStatuses=["); for (Entry<String, Boolean> entry : vertexGroupCommitStatus.entrySet()) { sb.append("{ vertexGroup=").append(entry.getKey()) .append(", committed=").append(entry.getValue()).append("}, "); } sb.append("]"); } return sb.toString(); } } private String isDAGRecoverable(DAGSummaryData data) { if (!data.dagCommitCompleted) { return "DAG Commit was in progress, not recoverable" + ", dagId=" + data.dagId; } if (!data.vertexCommitStatus.isEmpty()) { for (Entry<TezVertexID, Boolean> entry : data.vertexCommitStatus.entrySet()) { if (!(entry.getValue().booleanValue())) { return "Vertex Commit was in progress, not recoverable" + ", dagId=" + data.dagId + ", vertexId=" + entry.getKey(); } } } if (!data.vertexGroupCommitStatus.isEmpty()) { for (Entry<String, Boolean> entry : data.vertexGroupCommitStatus.entrySet()) { if (!(entry.getValue().booleanValue())) { return "Vertex Group Commit was in progress, not recoverable" + ", dagId=" + data.dagId + ", vertexGroup=" + entry.getKey(); } } } return null; } public RecoveredDAGData parseRecoveryData() throws IOException { Path previousAttemptRecoveryDataDir = getPreviousAttemptRecoveryDataDir(); LOG.info("Using " + previousAttemptRecoveryDataDir.toString() + " for recovering data from previous attempt"); if (!recoveryFS.exists(previousAttemptRecoveryDataDir)) { LOG.info("Nothing to recover as previous attempt data does not exist" + ", previousAttemptDir=" + previousAttemptRecoveryDataDir.toString()); createDataRecoveredFlagFile(); return null; } Path summaryPath = getSummaryPath(previousAttemptRecoveryDataDir); FSDataInputStream summaryStream = getSummaryStream( summaryPath); if (summaryStream == null) { LOG.info("Nothing to recover as summary file does not exist" + ", previousAttemptDir=" + previousAttemptRecoveryDataDir.toString() + ", summaryPath=" + summaryPath.toString()); createDataRecoveredFlagFile(); return null; } Path newSummaryPath = getSummaryPath(currentAttemptRecoveryDataDir); FSDataOutputStream newSummaryStream = getSummaryOutputStream(newSummaryPath); FileStatus summaryFileStatus = recoveryFS.getFileStatus(summaryPath); LOG.info("Parsing summary file" + ", path=" + summaryPath.toString() + ", len=" + summaryFileStatus.getLen() + ", lastModTime=" + summaryFileStatus.getModificationTime()); int dagCounter = 0; Map<TezDAGID, DAGSummaryData> dagSummaryDataMap = new HashMap<TezDAGID, DAGSummaryData>(); while (true) { RecoveryProtos.SummaryEventProto proto; try { proto = RecoveryProtos.SummaryEventProto.parseDelimitedFrom(summaryStream); if (proto == null) { LOG.info("Reached end of summary stream"); break; } } catch (EOFException eof) { LOG.info("Reached end of summary stream"); break; } HistoryEventType eventType = HistoryEventType.values()[proto.getEventType()]; if (LOG.isDebugEnabled()) { LOG.debug("[RECOVERY SUMMARY]" + " dagId=" + proto.getDagId() + ", timestamp=" + proto.getTimestamp() + ", event=" + eventType); } TezDAGID dagId = TezDAGID.fromString(proto.getDagId()); if (dagCounter < dagId.getId()) { dagCounter = dagId.getId(); } if (!dagSummaryDataMap.containsKey(dagId)) { dagSummaryDataMap.put(dagId, new DAGSummaryData(dagId)); } dagSummaryDataMap.get(dagId).handleSummaryEvent(proto); proto.writeDelimitedTo(newSummaryStream); } summaryStream.close(); newSummaryStream.hsync(); newSummaryStream.close(); // Set counter for next set of DAGs dagAppMaster.setDAGCounter(dagCounter); DAGSummaryData lastInProgressDAGData = getLastCompletedOrInProgressDAG(dagSummaryDataMap); if (lastInProgressDAGData == null) { LOG.info("Nothing to recover as no uncompleted/completed DAGs found"); return null; } TezDAGID lastInProgressDAG = lastInProgressDAGData.dagId; if (lastInProgressDAG == null) { LOG.info("Nothing to recover as no uncompleted/completed DAGs found"); return null; } LOG.info("Checking if DAG is in recoverable state" + ", dagId=" + lastInProgressDAGData.dagId); final RecoveredDAGData recoveredDAGData = new RecoveredDAGData(); if (lastInProgressDAGData.completed) { recoveredDAGData.isCompleted = true; recoveredDAGData.dagState = lastInProgressDAGData.dagState; } String nonRecoverableReason = isDAGRecoverable(lastInProgressDAGData); if (nonRecoverableReason != null) { LOG.warn("Found last inProgress DAG but not recoverable: " + lastInProgressDAGData); recoveredDAGData.nonRecoverable = true; recoveredDAGData.reason = nonRecoverableReason; } LOG.info("Trying to recover dag from recovery file" + ", dagId=" + lastInProgressDAG.toString() + ", dataDir=" + previousAttemptRecoveryDataDir + ", intoCurrentDir=" + currentAttemptRecoveryDataDir); FSDataInputStream dagRecoveryStream = getDAGRecoveryStream( previousAttemptRecoveryDataDir, lastInProgressDAG); if (dagRecoveryStream == null) { // Could not find data to recover // Error out throw new IOException("Could not find recovery data for last in progress DAG" + ", dagId=" + lastInProgressDAG); } LOG.info("Copying DAG data into Current Attempt directory" + ", filePath=" + getDAGRecoveryFilePath(currentAttemptRecoveryDataDir, lastInProgressDAG)); FSDataOutputStream newDAGRecoveryStream = getDAGRecoveryOutputStream(currentAttemptRecoveryDataDir, lastInProgressDAG); boolean skipAllOtherEvents = false; while (true) { HistoryEvent event; try { event = getNextEvent(dagRecoveryStream); if (event == null) { LOG.info("Reached end of dag recovery stream"); break; } } catch (EOFException eof) { LOG.info("Reached end of dag recovery stream"); break; } catch (IOException ioe) { LOG.warn("Corrupt data found when trying to read next event", ioe); break; } if (event == null || skipAllOtherEvents) { // reached end of data break; } HistoryEventType eventType = event.getEventType(); switch (eventType) { case DAG_SUBMITTED: { DAGSubmittedEvent submittedEvent = (DAGSubmittedEvent) event; LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); recoveredDAGData.recoveredDAG = dagAppMaster.createDAG(submittedEvent.getDAGPlan(), lastInProgressDAG); recoveredDAGData.cumulativeAdditionalResources = submittedEvent .getCumulativeAdditionalLocalResources(); recoveredDAGData.recoveredDagID = recoveredDAGData.recoveredDAG.getID(); dagAppMaster.setCurrentDAG(recoveredDAGData.recoveredDAG); if (recoveredDAGData.nonRecoverable) { skipAllOtherEvents = true; } break; } case DAG_INITIALIZED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); break; } case DAG_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); break; } case DAG_COMMIT_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); break; } case VERTEX_GROUP_COMMIT_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); break; } case VERTEX_GROUP_COMMIT_FINISHED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); break; } case DAG_FINISHED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); // If this is seen, nothing to recover assert recoveredDAGData.recoveredDAG != null; recoveredDAGData.recoveredDAG.restoreFromEvent(event); recoveredDAGData.isCompleted = true; recoveredDAGData.dagState = ((DAGFinishedEvent) event).getState(); skipAllOtherEvents = true; } case CONTAINER_LAUNCHED: { // Nothing to do for now break; } case VERTEX_INITIALIZED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexInitializedEvent vEvent = (VertexInitializedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } case VERTEX_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexStartedEvent vEvent = (VertexStartedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } case VERTEX_PARALLELISM_UPDATED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexParallelismUpdatedEvent vEvent = (VertexParallelismUpdatedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } case VERTEX_COMMIT_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexCommitStartedEvent vEvent = (VertexCommitStartedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } case VERTEX_FINISHED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexFinishedEvent vEvent = (VertexFinishedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } case TASK_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; TaskStartedEvent tEvent = (TaskStartedEvent) event; Task task = recoveredDAGData.recoveredDAG.getVertex( tEvent.getTaskID().getVertexID()).getTask(tEvent.getTaskID()); task.restoreFromEvent(tEvent); break; } case TASK_FINISHED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; TaskFinishedEvent tEvent = (TaskFinishedEvent) event; Task task = recoveredDAGData.recoveredDAG.getVertex( tEvent.getTaskID().getVertexID()).getTask(tEvent.getTaskID()); task.restoreFromEvent(tEvent); break; } case TASK_ATTEMPT_STARTED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; TaskAttemptStartedEvent tEvent = (TaskAttemptStartedEvent) event; Task task = recoveredDAGData.recoveredDAG.getVertex( tEvent.getTaskAttemptID().getTaskID().getVertexID()) .getTask(tEvent.getTaskAttemptID().getTaskID()); task.restoreFromEvent(tEvent); break; } case TASK_ATTEMPT_FINISHED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; TaskAttemptFinishedEvent tEvent = (TaskAttemptFinishedEvent) event; Task task = recoveredDAGData.recoveredDAG.getVertex( tEvent.getTaskAttemptID().getTaskID().getVertexID()) .getTask(tEvent.getTaskAttemptID().getTaskID()); task.restoreFromEvent(tEvent); break; } case VERTEX_DATA_MOVEMENT_EVENTS_GENERATED: { LOG.info("Recovering from event" + ", eventType=" + eventType + ", event=" + event.toString()); assert recoveredDAGData.recoveredDAG != null; VertexDataMovementEventsGeneratedEvent vEvent = (VertexDataMovementEventsGeneratedEvent) event; Vertex v = recoveredDAGData.recoveredDAG.getVertex(vEvent.getVertexID()); v.restoreFromEvent(vEvent); break; } default: throw new RuntimeException("Invalid data found, unknown event type " + eventType); } if (LOG.isDebugEnabled()) { LOG.debug("[DAG RECOVERY]" + " dagId=" + lastInProgressDAG + ", eventType=" + eventType + ", event=" + event.toString()); } newDAGRecoveryStream.writeInt(eventType.ordinal()); event.toProtoStream(newDAGRecoveryStream); } dagRecoveryStream.close(); newDAGRecoveryStream.hsync(); newDAGRecoveryStream.close(); if (!recoveredDAGData.isCompleted && !recoveredDAGData.nonRecoverable) { if (lastInProgressDAGData.bufferedSummaryEvents != null && !lastInProgressDAGData.bufferedSummaryEvents.isEmpty()) { for (HistoryEvent bufferedEvent : lastInProgressDAGData.bufferedSummaryEvents) { assert recoveredDAGData.recoveredDAG != null; switch (bufferedEvent.getEventType()) { case VERTEX_GROUP_COMMIT_STARTED: recoveredDAGData.recoveredDAG.restoreFromEvent(bufferedEvent); break; case VERTEX_GROUP_COMMIT_FINISHED: recoveredDAGData.recoveredDAG.restoreFromEvent(bufferedEvent); break; case VERTEX_FINISHED: VertexFinishedEvent vertexFinishedEvent = (VertexFinishedEvent) bufferedEvent; Vertex vertex = recoveredDAGData.recoveredDAG.getVertex( vertexFinishedEvent.getVertexID()); if (vertex == null) { recoveredDAGData.nonRecoverable = true; recoveredDAGData.reason = "All state could not be recovered" + ", vertex completed but events not flushed" + ", vertexId=" + vertexFinishedEvent.getVertexID(); } else { vertex.restoreFromEvent(vertexFinishedEvent); } break; default: throw new RuntimeException("Invalid data found in buffered summary events" + ", unknown event type " + bufferedEvent.getEventType()); } } } } LOG.info("Finished copying data from previous attempt into current attempt"); createDataRecoveredFlagFile(); return recoveredDAGData; } private void createDataRecoveredFlagFile() throws IOException { Path dataCopiedFlagPath = new Path(currentAttemptRecoveryDataDir, dataRecoveredFileFlag); LOG.info("Trying to create data recovered flag file" + ", filePath=" + dataCopiedFlagPath.toString()); recoveryFS.mkdirs(dataCopiedFlagPath); } }
apache/inlong
35,421
inlong-tubemq/tubemq-core/src/main/java/org/apache/inlong/tubemq/corebase/policies/FlowCtrlRuleHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.tubemq.corebase.policies; import org.apache.inlong.tubemq.corebase.TBaseConstants; import org.apache.inlong.tubemq.corebase.TokenConstants; import org.apache.inlong.tubemq.corebase.utils.TStringUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; /** * Flow control rule processing logic, including parsing the flow control json string, * obtaining the largest and smallest flow control values of each type to improve * the processing speed */ public class FlowCtrlRuleHandler { private final boolean isDefaultHandler; private final String flowCtrlName; private static final Logger logger = LoggerFactory.getLogger(FlowCtrlRuleHandler.class); private final TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00"); private final ReentrantLock writeLock = new ReentrantLock(); // Flow control ID and string information obtained from the server private AtomicLong flowCtrlId = new AtomicLong(TBaseConstants.META_VALUE_UNDEFINED); private AtomicInteger qryPriorityId = new AtomicInteger(TBaseConstants.META_VALUE_UNDEFINED); private String strFlowCtrlInfo; // The maximum interval of the flow control extracts the set of values, // improving the efficiency of the search return in the range private AtomicInteger minZeroCnt = new AtomicInteger(Integer.MAX_VALUE); private AtomicLong minDataLimitDlt = new AtomicLong(Long.MAX_VALUE); private AtomicInteger dataLimitStartTime = new AtomicInteger(2500); private AtomicInteger dataLimitEndTime = new AtomicInteger(TBaseConstants.META_VALUE_UNDEFINED); private FlowCtrlItem filterCtrlItem = new FlowCtrlItem(3, TBaseConstants.META_VALUE_UNDEFINED, TBaseConstants.META_VALUE_UNDEFINED, TBaseConstants.META_VALUE_UNDEFINED); private long lastUpdateTime = System.currentTimeMillis(); // Decoded flow control rules private Map<Integer, List<FlowCtrlItem>> flowCtrlRuleSet = new ConcurrentHashMap<>(); public FlowCtrlRuleHandler(boolean isDefault) { this.isDefaultHandler = isDefault; if (this.isDefaultHandler) { flowCtrlName = "Default_FlowCtrl"; } else { flowCtrlName = "Group_FlowCtrl"; } } /** * Parse flow control information and update stored cached old content * * @param qryPriorityId the query priority id * @param flowCtrlId flow control information id * @param flowCtrlInfo flow control information content * @param strBuff the string buffer * @throws Exception the exception thrown */ public void updateFlowCtrlInfo(int qryPriorityId, long flowCtrlId, String flowCtrlInfo, StringBuilder strBuff) throws Exception { if (flowCtrlId == this.flowCtrlId.get()) { return; } long befFlowCtrlId; int befQryPriorityId = TBaseConstants.META_VALUE_UNDEFINED; Map<Integer, List<FlowCtrlItem>> flowCtrlItemsMap = null; if (TStringUtils.isNotBlank(flowCtrlInfo)) { flowCtrlItemsMap = parseFlowCtrlInfo(flowCtrlInfo); } writeLock.lock(); try { befFlowCtrlId = this.flowCtrlId.getAndSet(flowCtrlId); this.strFlowCtrlInfo = flowCtrlInfo; clearStatisData(); if (flowCtrlItemsMap == null || flowCtrlItemsMap.isEmpty()) { this.flowCtrlRuleSet.clear(); } else { flowCtrlRuleSet = flowCtrlItemsMap; initialStatisData(); } if (qryPriorityId != TBaseConstants.META_VALUE_UNDEFINED && qryPriorityId != this.qryPriorityId.get()) { befQryPriorityId = this.qryPriorityId.getAndSet(qryPriorityId); } this.lastUpdateTime = System.currentTimeMillis(); } finally { writeLock.unlock(); } strBuff.append("[Flow Ctrl] Update ").append(flowCtrlName) .append(", flowId from ").append(befFlowCtrlId) .append(" to ").append(flowCtrlId); if (qryPriorityId != TBaseConstants.META_VALUE_UNDEFINED && qryPriorityId != befQryPriorityId) { strBuff.append(", qryPriorityId from ").append(befQryPriorityId) .append(" to ").append(qryPriorityId); } logger.info(strBuff.toString()); strBuff.delete(0, strBuff.length()); } /** * Get current data lag limit strategy * * @param lastDataDlt current consumption lag of data * @return FlowCtrlResult current flow control policy */ public FlowCtrlResult getCurDataLimit(long lastDataDlt) { Calendar rightNow = Calendar.getInstance(timeZone); int hour = rightNow.get(Calendar.HOUR_OF_DAY); int minu = rightNow.get(Calendar.MINUTE); int curTime = hour * 100 + minu; if (lastDataDlt < this.minDataLimitDlt.get() || curTime < this.dataLimitStartTime.get() || curTime > this.dataLimitEndTime.get()) { return null; } List<FlowCtrlItem> flowCtrlItemList = flowCtrlRuleSet.get(0); if (flowCtrlItemList == null || flowCtrlItemList.isEmpty()) { return null; } for (FlowCtrlItem flowCtrlItem : flowCtrlItemList) { if (flowCtrlItem == null) { continue; } FlowCtrlResult flowCtrlResult = flowCtrlItem.getDataLimit(lastDataDlt, hour, minu); if (flowCtrlResult != null) { return flowCtrlResult; } } return null; } public int getNormFreqInMs() { return this.filterCtrlItem.getFreqLtInMs(); } public int getMinDataFreqInMs() { return this.filterCtrlItem.getZeroCnt(); } public FlowCtrlItem getFilterCtrlItem() { return this.filterCtrlItem; } /** * Initial data limit statistics */ private void initialStatisData() { initialDataLimitStatisInfo(); initialFreqLimitStatisInfo(); initialLowFetchLimitStatisInfo(); } /** * Initial data limit statistics */ private void initialDataLimitStatisInfo() { List<FlowCtrlItem> flowCtrlItemList = this.flowCtrlRuleSet.get(0); if (flowCtrlItemList != null && !flowCtrlItemList.isEmpty()) { for (FlowCtrlItem flowCtrlItem : flowCtrlItemList) { if (flowCtrlItem == null) { continue; } if (flowCtrlItem.getType() != 0) { continue; } if (flowCtrlItem.getDltInM() < this.minDataLimitDlt.get()) { this.minDataLimitDlt.set(flowCtrlItem.getDltInM()); } if (flowCtrlItem.getStartTime() < this.dataLimitStartTime.get()) { this.dataLimitStartTime.set(flowCtrlItem.getStartTime()); } if (flowCtrlItem.getEndTime() > this.dataLimitEndTime.get()) { this.dataLimitEndTime.set(flowCtrlItem.getEndTime()); } } } } private void initialFreqLimitStatisInfo() { List<FlowCtrlItem> flowCtrlItemList = flowCtrlRuleSet.get(1); if (flowCtrlItemList != null && !flowCtrlItemList.isEmpty()) { for (FlowCtrlItem flowCtrlItem : flowCtrlItemList) { if (flowCtrlItem == null) { continue; } if (flowCtrlItem.getType() != 1) { continue; } if (flowCtrlItem.getZeroCnt() < this.minZeroCnt.get()) { this.minZeroCnt.set(flowCtrlItem.getZeroCnt()); } } } } private void initialLowFetchLimitStatisInfo() { List<FlowCtrlItem> flowCtrlItemList = flowCtrlRuleSet.get(3); if (flowCtrlItemList != null && !flowCtrlItemList.isEmpty()) { for (FlowCtrlItem flowCtrlItem : flowCtrlItemList) { if (flowCtrlItem == null) { continue; } if (flowCtrlItem.getType() != 3) { continue; } this.filterCtrlItem = new FlowCtrlItem(3, (int) flowCtrlItem.getDataLtInSZ(), flowCtrlItem.getFreqLtInMs(), flowCtrlItem.getZeroCnt()); } } } private void clearStatisData() { this.minZeroCnt.set(Integer.MAX_VALUE); this.minDataLimitDlt.set(Long.MAX_VALUE); this.dataLimitStartTime.set(2500); this.dataLimitEndTime.set(TBaseConstants.META_VALUE_UNDEFINED); this.filterCtrlItem = new FlowCtrlItem(3, TBaseConstants.META_VALUE_UNDEFINED, TBaseConstants.META_VALUE_UNDEFINED, TBaseConstants.META_VALUE_UNDEFINED); } public int getMinZeroCnt() { return minZeroCnt.get(); } /** * Get the current fetch frequency limit strategy * * @param msgZeroCnt the continuous consumption count without messages * @param rcmVal the default frequency limit value * @return the required frequency limit value */ public int getCurFreqLimitTime(int msgZeroCnt, int rcmVal) { if (msgZeroCnt < this.minZeroCnt.get()) { return rcmVal; } List<FlowCtrlItem> flowCtrlItemList = flowCtrlRuleSet.get(1); if (flowCtrlItemList == null || flowCtrlItemList.isEmpty()) { return rcmVal; } for (FlowCtrlItem flowCtrlItem : flowCtrlItemList) { if (flowCtrlItem == null) { continue; } int ruleVal = flowCtrlItem.getFreLimit(msgZeroCnt); if (ruleVal >= 0) { return ruleVal; } } return rcmVal; } public int getQryPriorityId() { return qryPriorityId.get(); } /** * Set query priority id value * @param qryPriorityId need to set value */ public void setQryPriorityId(int qryPriorityId) { this.qryPriorityId.set(qryPriorityId); } public long getFlowCtrlId() { return flowCtrlId.get(); } public void clear() { writeLock.lock(); try { this.strFlowCtrlInfo = ""; this.flowCtrlRuleSet.clear(); this.flowCtrlId.set(TBaseConstants.META_VALUE_UNDEFINED); this.qryPriorityId.set(TBaseConstants.META_VALUE_UNDEFINED); } finally { writeLock.unlock(); } } /** * Parse FlowCtrlInfo value * * @param flowCtrlInfo flowCtrlInfo json value * @return parse result * @throws Exception Exception thrown */ public Map<Integer, List<FlowCtrlItem>> parseFlowCtrlInfo(final String flowCtrlInfo) throws Exception { Map<Integer, List<FlowCtrlItem>> flowCtrlMap = new ConcurrentHashMap<>(); if (TStringUtils.isBlank(flowCtrlInfo)) { throw new Exception("Parsing error, flowCtrlInfo value is blank!"); } JsonArray objArray = null; try { objArray = JsonParser.parseString(flowCtrlInfo).getAsJsonArray(); } catch (Throwable e1) { throw new Exception("Parse flowCtrlInfo value failure", e1); } if (objArray == null) { throw new Exception("Parsing error, flowCtrlInfo value must be valid json format!"); } if (objArray.size() == 0) { return flowCtrlMap; } try { int recordNo; List<FlowCtrlItem> flowCtrlItemList; for (int i = 0; i < objArray.size(); i++) { JsonElement jsonItem = objArray.get(i); if (jsonItem == null) { continue; } recordNo = i + 1; JsonObject jsonObject = jsonItem.getAsJsonObject(); if (!jsonObject.has("type")) { throw new Exception(new StringBuilder(512) .append("FIELD type is required in record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } int typeVal = jsonObject.get("type").getAsInt(); if (typeVal < 0 || typeVal > 3) { throw new Exception(new StringBuilder(512) .append("the value of FIELD type must in [0,1,3] in record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } switch (typeVal) { case 1: flowCtrlItemList = parseFreqLimit(recordNo, typeVal, jsonObject); break; case 2: /* Deprecated */ flowCtrlItemList = null; break; case 3: flowCtrlItemList = parseLowFetchLimit(recordNo, typeVal, jsonObject); break; case 0: default: typeVal = 0; flowCtrlItemList = parseDataLimit(recordNo, typeVal, jsonObject); break; } if (flowCtrlItemList != null && !flowCtrlItemList.isEmpty()) { flowCtrlMap.put(typeVal, flowCtrlItemList); } } } catch (Throwable e2) { throw new Exception(new StringBuilder(512) .append("Parse flowCtrlInfo value failure, ") .append(e2.getMessage()).toString()); } return flowCtrlMap; } /** * lizard forgives * * Parse data consumption limit rule info * * @param recordNo record no * @param typeVal type value * @param jsonObject record json value * @return parsed result * @throws Exception Exception thrown */ private List<FlowCtrlItem> parseDataLimit(int recordNo, int typeVal, JsonObject jsonObject) throws Exception { if (jsonObject == null || jsonObject.get("type").getAsInt() != 0) { throw new Exception(new StringBuilder(512) .append("parse data_limit rule failure in record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } if (!jsonObject.has("rule")) { throw new Exception(new StringBuilder(512) .append("FIELD rule is required in data_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } JsonArray ruleArray = jsonObject.get("rule").getAsJsonArray(); if (ruleArray == null) { throw new Exception(new StringBuilder(512) .append("emtpy rule define in data_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } // parse rule item int itemNo; ArrayList<FlowCtrlItem> flowCtrlItems = new ArrayList<>(); for (int index = 0; index < ruleArray.size(); index++) { itemNo = index + 1; JsonObject ruleObject = ruleArray.get(index).getAsJsonObject(); int startTime = validAndGetTimeValue(ruleObject, "start", itemNo, recordNo); int endTime = validAndGetTimeValue(ruleObject, "end", itemNo, recordNo); if (startTime >= endTime) { throw new Exception(new StringBuilder(512) .append("the value of FIELD start must lower than the value FIELD end ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (!ruleObject.has("dltInM")) { throw new Exception(new StringBuilder(512) .append("FIELD dltInM is required in data_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } long dltVal = ruleObject.get("dltInM").getAsLong(); if (dltVal <= 20) { throw new Exception(new StringBuilder(512) .append("the value of FIELD dltInM must be greater than 20 ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (!ruleObject.has("limitInM")) { throw new Exception(new StringBuilder(512) .append("FIELD limitInM is required in data_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } long dataLimitInM = ruleObject.get("limitInM").getAsLong(); if (dataLimitInM < 0) { throw new Exception(new StringBuilder(512) .append("the value of FIELD limitInM must be greater than or equal to 0 ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } dataLimitInM = dataLimitInM * 1024 * 1024; if (!ruleObject.has("freqInMs")) { throw new Exception(new StringBuilder(512) .append("FIELD freqInMs is required in data_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } int freqInMs = ruleObject.get("freqInMs").getAsInt(); if (freqInMs < 200) { throw new Exception(new StringBuilder(512) .append("the value of FIELD freqInMs must be greater than or equal to 200 ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } flowCtrlItems.add(new FlowCtrlItem(typeVal, startTime, endTime, dltVal, dataLimitInM, freqInMs)); } if (flowCtrlItems.isEmpty()) { throw new Exception(new StringBuilder(512) .append("not found valid rule define in data_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } Collections.sort(flowCtrlItems, new Comparator<FlowCtrlItem>() { @Override public int compare(final FlowCtrlItem o1, final FlowCtrlItem o2) { if (o1.getStartTime() > o2.getStartTime()) { return 1; } else if (o1.getStartTime() < o2.getStartTime()) { return -1; } else { return 0; } } }); return flowCtrlItems; } /** * Parse frequent limit rule info * * @param recordNo record no * @param typeVal type value * @param jsonObject record json value * @return parsed result * @throws Exception Exception thrown */ private List<FlowCtrlItem> parseFreqLimit(int recordNo, int typeVal, JsonObject jsonObject) throws Exception { if (jsonObject == null || jsonObject.get("type").getAsInt() != 1) { throw new Exception(new StringBuilder(512) .append("parse freq_limit rule failure in record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } if (!jsonObject.has("rule")) { throw new Exception(new StringBuilder(512) .append("FIELD rule is required in freq_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } JsonArray ruleArray = jsonObject.get("rule").getAsJsonArray(); if (ruleArray == null) { throw new Exception(new StringBuilder(512) .append("emtpy rule define in freq_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } int itemNo; ArrayList<FlowCtrlItem> flowCtrlItems = new ArrayList<>(); for (int index = 0; index < ruleArray.size(); index++) { itemNo = index + 1; JsonObject ruleObject = ruleArray.get(index).getAsJsonObject(); if (!ruleObject.has("zeroCnt")) { throw new Exception(new StringBuilder(512) .append("FIELD zeroCnt is required in freq_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } int zeroCnt = ruleObject.get("zeroCnt").getAsInt(); if (zeroCnt < 1) { throw new Exception(new StringBuilder(512) .append("the value of FIELD zeroCnt must be greater than or equal to 1 ") .append("in freq_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (!ruleObject.has("freqInMs")) { throw new Exception(new StringBuilder(512) .append("FIELD freqInMs is required in freq_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } int freqInMs = ruleObject.get("freqInMs").getAsInt(); if (freqInMs < 0) { throw new Exception(new StringBuilder(512) .append("the value of FIELD freqInMs must be greater than or equal to 0 ") .append("in freq_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } flowCtrlItems.add(new FlowCtrlItem(typeVal, zeroCnt, freqInMs)); } if (flowCtrlItems.isEmpty()) { throw new Exception(new StringBuilder(512) .append("not found valid rule define in freq_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } // sort rule set by the value of FIELD zeroCnt Collections.sort(flowCtrlItems, new Comparator<FlowCtrlItem>() { @Override public int compare(final FlowCtrlItem o1, final FlowCtrlItem o2) { if (o1.getZeroCnt() > o2.getZeroCnt()) { return -1; } else if (o1.getZeroCnt() < o2.getZeroCnt()) { return 1; } else { return 0; } } }); return flowCtrlItems; } /** * Parse low frequent fetch count * * @param recordNo record no * @param typeVal type value * @param jsonObject record json value * @return parsed result * @throws Exception Exception thrown */ private List<FlowCtrlItem> parseLowFetchLimit(int recordNo, int typeVal, JsonObject jsonObject) throws Exception { if (jsonObject == null || jsonObject.get("type").getAsInt() != 3) { throw new Exception(new StringBuilder(512) .append("parse low_fetch_limit rule failure in record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } if (!jsonObject.has("rule")) { throw new Exception(new StringBuilder(512) .append("FIELD rule is required in low_fetch_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } JsonArray ruleArray = jsonObject.get("rule").getAsJsonArray(); if (ruleArray == null) { throw new Exception(new StringBuilder(512) .append("emtpy rule define in low_fetch_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } if (ruleArray.size() > 1) { throw new Exception(new StringBuilder(512) .append("only allow set one rule in low_fetch_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } int itemNo; ArrayList<FlowCtrlItem> flowCtrlItems = new ArrayList<>(); // parse low_fetch_limit rule record for (int index = 0; index < ruleArray.size(); index++) { itemNo = index + 1; JsonObject ruleObject = ruleArray.get(index).getAsJsonObject(); int normfreqInMs = 0; int filterFreqInMs = 0; int minDataFilterFreqInMs = 0; if (ruleObject.has("filterFreqInMs") || ruleObject.has("minDataFilterFreqInMs")) { if (!ruleObject.has("filterFreqInMs")) { throw new Exception(new StringBuilder(512) .append("FIELD filterFreqInMs is required ") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } filterFreqInMs = ruleObject.get("filterFreqInMs").getAsInt(); if (filterFreqInMs < 0 || filterFreqInMs > 300000) { throw new Exception(new StringBuilder(512) .append("the value of FIELD filterFreqInMs must in [0, 300000] ") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (!ruleObject.has("minDataFilterFreqInMs")) { throw new Exception(new StringBuilder(512) .append("FIELD minDataFilterFreqInMs is required ") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } minDataFilterFreqInMs = ruleObject.get("minDataFilterFreqInMs").getAsInt(); if (minDataFilterFreqInMs < 0 || minDataFilterFreqInMs > 300000) { throw new Exception(new StringBuilder(512) .append("the value of FIELD minDataFilterFreqInMs must in [0, 300000] ") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (minDataFilterFreqInMs < filterFreqInMs) { throw new Exception(new StringBuilder(512) .append("the value of FIELD minDataFilterFreqInMs must be greater ") .append("than or equal to the value of FIELD filterFreqInMs") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } } if (ruleObject.has("normFreqInMs")) { normfreqInMs = ruleObject.get("normFreqInMs").getAsInt(); if (normfreqInMs < 0 || normfreqInMs > 300000) { throw new Exception(new StringBuilder(512) .append("the value of FIELD normFreqInMs must in [0, 300000] ") .append("in low_fetch_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } } flowCtrlItems.add(new FlowCtrlItem(typeVal, normfreqInMs, filterFreqInMs, minDataFilterFreqInMs)); } if (flowCtrlItems.isEmpty()) { throw new Exception(new StringBuilder(512) .append("not found valid rule define in low_fetch_limit record(") .append(recordNo).append(") of flowCtrlInfo value!").toString()); } // sort rule set by the value of filterFreqInMs Collections.sort(flowCtrlItems, new Comparator<FlowCtrlItem>() { @Override public int compare(final FlowCtrlItem o1, final FlowCtrlItem o2) { if (o1.getFreqLtInMs() > o2.getFreqLtInMs()) { return -1; } else if (o1.getFreqLtInMs() < o2.getFreqLtInMs()) { return 1; } else { return 0; } } }); return flowCtrlItems; } @Override public String toString() { return this.strFlowCtrlInfo; } /** * Parse time information * * @param ruleObject rule value object * @param fieldName field name * @param itemNo rule no * @param recordNo record no * @return parse result * @throws Exception Exception thrown */ private int validAndGetTimeValue(JsonObject ruleObject, String fieldName, int itemNo, int recordNo) throws Exception { if (!ruleObject.has(fieldName)) { throw new Exception(new StringBuilder(512) .append("FIELD ").append(fieldName).append(" is required ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } String strTimeVal = ruleObject.get(fieldName).getAsString(); if (TStringUtils.isBlank(strTimeVal)) { throw new Exception(new StringBuilder(512) .append("the value of FIELD ").append(fieldName) .append(" is null or blank in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } int timeHour = 0; int timeMin = 0; String[] startItems = strTimeVal.split(TokenConstants.ATTR_SEP); if ((startItems.length != 2) || TStringUtils.isBlank(startItems[0]) || TStringUtils.isBlank(startItems[1])) { throw new Exception(new StringBuilder(512) .append("illegal format, the value of FIELD ").append(fieldName) .append(" must be 'aa:bb' and 'aa','bb' must be int value ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } try { timeHour = Integer.parseInt(startItems[0]); } catch (Throwable e2) { throw new Exception(new StringBuilder(512) .append("illegal format, the value of FIELD ").append(fieldName) .append(" must be 'aa:bb' and 'aa' must be int value ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } try { timeMin = Integer.parseInt(startItems[1]); } catch (Throwable e2) { throw new Exception(new StringBuilder(512) .append("illegal format, the value of FIELD ").append(fieldName) .append(" must be 'aa:bb' and 'bb' must be int value ") .append("in data_limit item(").append(itemNo) .append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (timeHour < 0 || timeHour > 24) { throw new Exception(new StringBuilder(512) .append("illegal value, the value of FIELD ").append(fieldName) .append("-hour value must in [0,23] in data_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } if (timeMin < 0 || timeMin > 59) { throw new Exception(new StringBuilder(512) .append("illegal value, the value of FIELD ").append(fieldName) .append("-minute value must in [0,59] in data_limit item(") .append(itemNo).append(").record(").append(recordNo) .append(") of flowCtrlInfo value!").toString()); } return timeHour * 100 + timeMin; } }
oracle/coherence
35,501
prj/coherence-grpc/src/main/java/com/oracle/coherence/grpc/internal/extend/messageFactory/GrpcNamedTopicFactory.java
/* * Copyright (c) 2000, 2025, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.oracle.coherence.grpc.internal.extend.messageFactory; import com.google.protobuf.Any; import com.google.protobuf.BoolValue; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import com.oracle.coherence.common.base.Exceptions; import com.oracle.coherence.grpc.BinaryHelper; import com.oracle.coherence.grpc.ErrorsHelper; import com.oracle.coherence.grpc.MessageHelper; import com.oracle.coherence.grpc.TopicHelper; import com.oracle.coherence.grpc.messages.topic.v1.SimpleReceiveResponse; import com.oracle.coherence.grpc.messages.topic.v1.TopicElement; import com.tangosol.coherence.component.net.extend.message.GrpcMessageWrapper; import com.tangosol.coherence.component.net.extend.messageFactory.GrpcMessageFactory; import com.oracle.coherence.grpc.internal.extend.message.response.BoolValueResponse; import com.oracle.coherence.grpc.internal.extend.message.response.CollectionOfInt32Response; import com.oracle.coherence.grpc.internal.extend.message.response.EmptyResponse; import com.oracle.coherence.grpc.internal.extend.message.response.Int32ValueResponse; import com.oracle.coherence.grpc.internal.extend.message.response.MapOfChannelAndPositionResponse; import com.oracle.coherence.grpc.messages.common.v1.CollectionOfInt32; import com.oracle.coherence.grpc.messages.topic.v1.ChannelAndPosition; import com.oracle.coherence.grpc.messages.topic.v1.CommitResponse; import com.oracle.coherence.grpc.messages.topic.v1.CommitResponseStatus; import com.oracle.coherence.grpc.messages.topic.v1.InitializeSubscriptionResponse; import com.oracle.coherence.grpc.messages.topic.v1.NamedTopicEvent; import com.oracle.coherence.grpc.messages.topic.v1.ReceiveResponse; import com.oracle.coherence.grpc.messages.topic.v1.ReceiveStatus; import com.oracle.coherence.grpc.messages.topic.v1.ResponseType; import com.oracle.coherence.grpc.messages.topic.v1.SeekedPositions; import com.oracle.coherence.grpc.messages.topic.v1.TopicEventType; import com.oracle.coherence.grpc.messages.topic.v1.TopicPosition; import com.oracle.coherence.grpc.messages.topic.v1.TopicServiceRequest; import com.oracle.coherence.grpc.messages.topic.v1.TopicServiceResponse; import com.tangosol.coherence.component.net.extend.message.response.GrpcResponse; import com.tangosol.coherence.component.net.extend.messageFactory.NamedTopicFactory; import com.tangosol.internal.net.topic.PublishResult; import com.tangosol.internal.net.topic.SeekResult; import com.tangosol.internal.net.topic.SimpleReceiveResult; import com.tangosol.internal.net.topic.impl.paged.model.PageElement; import com.tangosol.io.Serializer; import com.tangosol.net.topic.Position; import com.tangosol.net.topic.Subscriber; import com.tangosol.util.Binary; import com.tangosol.util.Filter; import com.tangosol.util.ListMap; import com.tangosol.util.ValueExtractor; import java.util.Arrays; import java.util.List; import java.util.Map; /** * A {@link NamedTopicFactory} that provides messages * that wrap protobuf messages. * * @author Jonathan Knight 2025.01.25 */ public class GrpcNamedTopicFactory extends NamedTopicFactory implements GrpcMessageFactory<TopicServiceRequest, TopicServiceResponse> { public GrpcNamedTopicFactory() { } static { __initStatic(); } private static void __initStatic() { // register child classes __mapChildren = new ListMap<>(); __mapChildren.put("GetRemainingMessagesRequest", GrpcGetRemainingMessagesRequest.class); __mapChildren.put("EnsureSubscriberGroupRequest", GrpcEnsureSubscriberGroupRequest.class); __mapChildren.put("DestroySubscriberGroupRequest", GrpcDestroySubscriberGroupRequest.class); __mapChildren.put("PublishRequest", GrpcPublishRequest.class); __mapChildren.put("InitializeSubscriptionRequest", GrpcInitializeSubscriptionRequest.class); __mapChildren.put("EnsureSubscriptionRequest", GrpcEnsureSubscriptionRequest.class); __mapChildren.put("GetOwnedChannelsRequest", GrpcGetOwnedChannelsRequest.class); __mapChildren.put("ReceiveRequest", GrpcReceiveRequest.class); __mapChildren.put("SimpleReceiveRequest", GrpcSimpleReceiveRequest.class); __mapChildren.put("PeekRequest", GrpcPeekRequest.class); __mapChildren.put("CommitRequest", GrpcCommitRequest.class); __mapChildren.put("IsCommitedRequest", GrpcIsCommitedRequest.class); __mapChildren.put("GetLastCommitedRequest", GrpcGetLastCommitedRequest.class); __mapChildren.put("GetHeadsRequest", GrpcGetHeadsRequest.class); __mapChildren.put("GetTailsRequest", GrpcGetTailsRequest.class); __mapChildren.put("SeekRequest", GrpcSeekRequest.class); __mapChildren.put("HeartbeatRequest", GrpcHeartbeatRequest.class); __mapChildren.put("Response", TopicsResponse.class); __mapChildren.put("PublisherEvent", PublisherEvent.class); __mapChildren.put("GetSubscription", GetSubscriptionRequest.class); __mapChildren.put("SubscriberEvent", SubscriberChannelEvent.class); __mapChildren.put("DestroyEvent", DestroyEvent.class); } @Override protected Map<String, Class<?>> get_ChildClasses() { return __mapChildren; } @Override @SuppressWarnings({"unchecked"}) public <M extends GrpcMessageWrapper> M createRequestMessage(TopicServiceRequest request, Serializer serializer) { M message = (M) switch (request.getType()) { case EnsureSubscriberGroup -> createMessage(TYPE_ID_ENSURE_SUBSCRIBER_GROUP); case DestroySubscriberGroup -> createMessage(TYPE_ID_DESTROY_SUBSCRIBER_GROUP); case GetRemainingMessages -> createMessage(TYPE_ID_REMAINING_MESSAGES); case GetTails -> createMessage(TYPE_ID_GET_TAILS); case Publish -> createMessage(TYPE_ID_PUBLISH); case InitializeSubscription -> createMessage(TYPE_ID_INITIALIZE_SUBSCRIPTION); case EnsureSubscription -> createMessage(TYPE_ID_ENSURE_SUBSCRIPTION); case GetSubscriberHeads -> createMessage(TYPE_ID_GET_HEADS); case GetLastCommited -> createMessage(TYPE_ID_GET_LAST_COMMITTED); case GetOwnedChannels -> createMessage(TYPE_ID_GET_OWNED_CHANNELS); case SubscriberHeartbeat -> createMessage(TYPE_ID_HEARTBEAT); case IsPositionCommitted -> createMessage(TYPE_ID_IS_COMMITTED); case PeekAtPosition -> createMessage(TYPE_ID_PEEK); case Receive -> createMessage(TYPE_ID_RECEIVE); case SimpleReceive -> createMessage(TYPE_ID_SIMPLE_RECEIVE); case SeekSubscriber -> createMessage(TYPE_ID_SEEK); case CommitPosition -> createMessage(TYPE_ID_COMMIT); default -> throw new IllegalArgumentException("Unsupported request type: " + request.getType()); }; if (request.hasMessage()) { message.setProtoMessage(request.getMessage(), serializer); } return message; } @Override public TopicServiceResponse createResponse(GrpcResponse response) { Message protoResponse = response.getProtoResponse(); // Must return the populated TopicServiceResponse TopicServiceResponse.Builder builder = TopicServiceResponse.newBuilder() .setProxyId(response.getProxyId()) .setMessage(Any.pack(protoResponse)); return builder.build(); } @Override public TopicServiceResponse toProtoMessage(com.tangosol.net.messaging.Message message, int nProxyId) { int nTypeId = message.getTypeId(); ResponseType responseType; if (nTypeId == TYPE_ID_PUBLISHER_EVENT || nTypeId == TYPE_ID_SUBSCRIBER_EVENT || nTypeId == TYPE_ID_DESTROY_EVENT) { responseType = ResponseType.Event; TopicServiceResponse.Builder builder = TopicServiceResponse.newBuilder() .setProxyId(nProxyId) .setType(responseType); Message payload = switch (nTypeId) { case TYPE_ID_PUBLISHER_EVENT -> TopicHelper.toProtobufPublisherEvent((PublisherEvent) message); case TYPE_ID_DESTROY_EVENT -> NamedTopicEvent.newBuilder().setType(TopicEventType.TopicDestroyed).build(); case TYPE_ID_SUBSCRIBER_EVENT -> TopicHelper.toProtobufSubscriberEvent((SubscriberChannelEvent) message); default -> throw new IllegalArgumentException("Unsupported message type: " + message); }; builder.setMessage(Any.pack(payload)); return builder.build(); } return null; } // ----- helper methods ------------------------------------------------- /** * Unpack the message field from a request. * * @param request the request to get the message from * @param type the expected type of the message * @param <T> the expected type of the message * @return the unpacked message */ protected <T extends Message> T unpack(TopicServiceRequest request, Class<T> type) { try { Any any = request.getMessage(); return any.unpack(type); } catch (InvalidProtocolBufferException e) { throw Exceptions.ensureRuntimeException(e, "Could not unpack message field of type " + type.getName()); } } // ----- inner class: GrpcGetRemainingMessagesRequest ------------------- /** * The gRPC {@link GrpcGetRemainingMessagesRequest} which wraps a protobuf request. */ public static class GrpcGetRemainingMessagesRequest extends GetRemainingMessagesRequest implements GrpcMessageWrapper { public GrpcGetRemainingMessagesRequest() { setResponse(new Int32ValueResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.GetRemainingMessagesRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.GetRemainingMessagesRequest.class); setSubscriberGroup(request.getSubscriberGroup()); List<Integer> list = request.getChannelsList(); setChannels(list.stream().mapToInt(i -> i).toArray()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcEnsureSubscriberGroupRequest ------------------ /** * The gRPC {@link GrpcEnsureSubscriberGroupRequest} which wraps a protobuf request. */ public static class GrpcEnsureSubscriberGroupRequest extends EnsureSubscriberGroupRequest implements GrpcMessageWrapper { public GrpcEnsureSubscriberGroupRequest() { setResponse(new EmptyResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.EnsureSubscriberGroupRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.EnsureSubscriberGroupRequest.class); setSubscriberGroup(request.getSubscriberGroup()); if (request.hasFilter()) { Filter<?> filter = BinaryHelper.fromByteString(request.getFilter(), serializer); setFilter(filter); } if (request.hasExtractor()) { ValueExtractor<?, ?> extractor = BinaryHelper.fromByteString(request.getExtractor(), serializer); setExtractor(extractor); } } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcDestroySubscriberGroupRequest ----------------- /** * The gRPC {@link GrpcDestroySubscriberGroupRequest} which wraps a protobuf request. */ public static class GrpcDestroySubscriberGroupRequest extends DestroySubscriberGroupRequest implements GrpcMessageWrapper { public GrpcDestroySubscriberGroupRequest() { setResponse(new EmptyResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { StringValue sGroup = MessageHelper.unpack(any, StringValue.class); setSubscriberGroup(sGroup.getValue()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcPublishRequest -------------------------------- /** * The gRPC {@link GrpcPublishRequest} which wraps a protobuf request. */ public static class GrpcPublishRequest extends PublishRequest implements GrpcMessageWrapper { public GrpcPublishRequest() { setResponse(new GrpcPublishResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.PublishRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.PublishRequest.class); setChannel(request.getChannel()); setBinaries(BinaryHelper.toListOfBinary(request.getValuesList())); if (request.hasNotificationIdentifier()) { setNotify(request.getNotificationIdentifier()); } } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcPublishResponseRequest ------------------------ /** * The response for a {@link GrpcPublishRequest} request. */ public static class GrpcPublishResponse extends GrpcResponse { public GrpcPublishResponse() { } @Override public Message getProtoResponse() { PublishResult result = (PublishResult) getResult(); return TopicHelper.toProtobufPublishResult(result, m_serializer); } } // ----- inner class: GrpcInitializeSubscriptionRequest ----------------- /** * The gRPC {@link GrpcEnsureSubscriptionRequest} which wraps a protobuf request. */ public static class GrpcInitializeSubscriptionRequest extends InitializeSubscriptionRequest implements GrpcMessageWrapper { public GrpcInitializeSubscriptionRequest() { setResponse(new GrpcInitializeSubscriptionResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.InitializeSubscriptionRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.InitializeSubscriptionRequest.class); setDisconnected(request.getDisconnected()); setReconnect(request.getReconnect()); setForceReconnect(request.getForceReconnect()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcInitializeSubscriptionResponseRequest --------- /** * The response for a {@link GrpcInitializeSubscriptionRequest} request. */ public static class GrpcInitializeSubscriptionResponse extends GrpcResponse { public GrpcInitializeSubscriptionResponse() { } @Override public Message getProtoResponse() { Object[] aoResult = (Object[]) getResult(); Timestamp timestamp = Timestamps.fromMillis((Long) aoResult[1]); Object[] aoPosition = (Object[]) aoResult[2]; List<TopicPosition> heads = Arrays.stream(aoPosition) .map(o -> TopicHelper.toProtobufPosition((Position) o)) .toList(); return InitializeSubscriptionResponse.newBuilder() .setSubscriptionId((Long) aoResult[0]) .setTimestamp(timestamp) .addAllHeads(heads) .build(); } } // ----- inner class: GrpcEnsureSubscriptionRequest --------------------- /** * The gRPC {@link GrpcEnsureSubscriptionRequest} which wraps a protobuf request. */ public static class GrpcEnsureSubscriptionRequest extends EnsureSubscriptionRequest implements GrpcMessageWrapper { public GrpcEnsureSubscriptionRequest() { setResponse(new BoolValueResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.EnsureSubscriptionRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.EnsureSubscriptionRequest.class); setSubscriptionId(request.getSubscriptionId()); setForceReconnect(request.getForceReconnect()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcGetOwnedChannelsRequest ----------------------- /** * The gRPC {@link GrpcGetOwnedChannelsRequest} which wraps a protobuf request. */ public static class GrpcGetOwnedChannelsRequest extends GetOwnedChannelsRequest implements GrpcMessageWrapper { public GrpcGetOwnedChannelsRequest() { setResponse(new CollectionOfInt32Response()); } @Override public void setProtoMessage(Any any, Serializer serializer) { } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcReceiveRequest -------------------------------- /** * The gRPC {@link GrpcReceiveRequest} which wraps a protobuf request. */ public static class GrpcReceiveRequest extends ReceiveRequest implements GrpcMessageWrapper { public GrpcReceiveRequest() { setResponse(new GrpcReceiveResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.ReceiveRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.ReceiveRequest.class); setTopicChannel(request.getChannel()); setMaxElements(request.getMaxMessages()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcReceiveRequest -------------------------------- /** * The gRPC {@link GrpcSimpleReceiveRequest} which wraps a protobuf request. */ public static class GrpcSimpleReceiveRequest extends SimpleReceiveRequest implements GrpcMessageWrapper { public GrpcSimpleReceiveRequest() { setResponse(new GrpcSimpleReceiveResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.SimpleReceiveRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.SimpleReceiveRequest.class); int cMaxMessages = request.getMaxMessages(); setMaxElements(Math.max(1, cMaxMessages)); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcReceiveResponseRequest ------------------------ /** * The response for a {@link GrpcReceiveRequest} request. */ public static class GrpcReceiveResponse extends GrpcResponse { public GrpcReceiveResponse() { } @Override public Message getProtoResponse() { Object oResult = getResult(); if (oResult instanceof Throwable) { return ErrorsHelper.createErrorMessage((Throwable) oResult, m_serializer); } SimpleReceiveResult result = (SimpleReceiveResult) oResult; ReceiveStatus status = switch (result.getStatus()) { case Success -> ReceiveStatus.ReceiveSuccess; case Exhausted -> ReceiveStatus.ChannelExhausted; case NotAllocatedChannel -> ReceiveStatus.ChannelNotAllocatedChannel; case UnknownSubscriber -> ReceiveStatus.UnknownSubscriber; }; ReceiveResponse.Builder builder = ReceiveResponse.newBuilder() .setHeadPosition(TopicHelper.toProtobufPosition(result.getHead())) .setRemainingValues(result.getRemainingElementCount()) .setStatus(status); for (Binary binary : result.getElements()) { builder.addValues(BinaryHelper.toByteString(binary)); } return builder.build(); } } // ----- inner class: GrpcReceiveResponseRequest ------------------------ /** * The response for a {@link GrpcSimpleReceiveRequest} request. */ public static class GrpcSimpleReceiveResponse extends GrpcResponse { public GrpcSimpleReceiveResponse() { } @Override public Message getProtoResponse() { Object oResult = getResult(); if (oResult instanceof Throwable) { return ErrorsHelper.createErrorMessage((Throwable) oResult, m_serializer); } SimpleReceiveResult result = (SimpleReceiveResult) oResult; ReceiveStatus status = switch (result.getStatus()) { case Success -> ReceiveStatus.ReceiveSuccess; case Exhausted -> ReceiveStatus.ChannelExhausted; case NotAllocatedChannel -> ReceiveStatus.ChannelNotAllocatedChannel; case UnknownSubscriber -> ReceiveStatus.UnknownSubscriber; }; SimpleReceiveResponse.Builder builder = SimpleReceiveResponse.newBuilder() .setStatus(status); for (Binary binary : result.getElements()) { TopicElement element = TopicHelper.toProtobufTopicElement(PageElement.fromBinary(binary, m_serializer)); builder.addValues(element); } return builder.build(); } } // ----- inner class: GrpcPeekRequest ----------------------------------- /** * The gRPC {@link GrpcPeekRequest} which wraps a protobuf request. */ public static class GrpcPeekRequest extends PeekRequest implements GrpcMessageWrapper { public GrpcPeekRequest() { setResponse(new GrpcPeekResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { ChannelAndPosition cp = MessageHelper.unpack(any, ChannelAndPosition.class); setChannel(cp.getChannel()); setPosition(TopicHelper.fromProtobufPosition(cp.getPosition())); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcPeekResponse ---------------------------------- /** * The response for a {@link GrpcPeekRequest} request. */ public static class GrpcPeekResponse extends GrpcResponse { public GrpcPeekResponse() { } @Override public Message getProtoResponse() { Subscriber.Element<?> element = (Subscriber.Element<?>) getResult(); return TopicHelper.toProtobufTopicElement(element); } } // ----- inner class: GrpcCommitRequest --------------------------------- /** * The gRPC {@link GrpcCommitRequest} which wraps a protobuf request. */ public static class GrpcCommitRequest extends CommitRequest implements GrpcMessageWrapper { public GrpcCommitRequest() { setResponse(new GrpcCommitResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { ChannelAndPosition cp = MessageHelper.unpack(any, ChannelAndPosition.class); setChannel(cp.getChannel()); setPosition(TopicHelper.fromProtobufPosition(cp.getPosition())); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcCommitResponse -------------------------------- /** * The response for a {@link GrpcCommitRequest} request. */ public static class GrpcCommitResponse extends GrpcResponse { public GrpcCommitResponse() { } @Override public Message getProtoResponse() { Object[] aoResult = (Object[]) getResult(); TopicPosition head = TopicHelper.toProtobufPosition((Position) aoResult[CommitRequest.RESPONSE_ID_HEAD]); Subscriber.CommitResult result = (Subscriber.CommitResult) aoResult[CommitRequest.RESPONSE_ID_RESULT]; CommitResponseStatus status = switch (result.getStatus()) { case Committed -> CommitResponseStatus.Committed; case AlreadyCommitted -> CommitResponseStatus.AlreadyCommitted; case Rejected -> CommitResponseStatus.Rejected; case Unowned -> CommitResponseStatus.Unowned; case NothingToCommit -> CommitResponseStatus.NothingToCommit; }; CommitResponse.Builder builder = CommitResponse.newBuilder() .setHead(head) .setStatus(status); result.getChannel().ifPresent(builder::setChannel); result.getError().ifPresent(err -> builder.setError(ErrorsHelper.createErrorMessage(err, m_serializer))); result.getPosition().ifPresent(pos -> builder.setPosition(TopicHelper.toProtobufPosition(pos))); return builder.build(); } } // ----- inner class: GrpcIsCommitedRequest ----------------------------- /** * The gRPC {@link GrpcIsCommitedRequest} which wraps a protobuf request. */ public static class GrpcIsCommitedRequest extends IsCommitedRequest implements GrpcMessageWrapper { public GrpcIsCommitedRequest() { setResponse(new BoolValueResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { ChannelAndPosition cp = MessageHelper.unpack(any, ChannelAndPosition.class); setChannel(cp.getChannel()); setPosition(TopicHelper.fromProtobufPosition(cp.getPosition())); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcGetLastCommitedRequest ------------------------ /** * The gRPC {@link GrpcGetLastCommitedRequest} which wraps a protobuf request. */ public static class GrpcGetLastCommitedRequest extends GetLastCommitedRequest implements GrpcMessageWrapper { public GrpcGetLastCommitedRequest() { setResponse(new MapOfChannelAndPositionResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcGetHeadsRequest ------------------------------- /** * The gRPC {@link GrpcGetTailsRequest} which wraps a protobuf request. */ public static class GrpcGetHeadsRequest extends GetHeadsRequest implements GrpcMessageWrapper { public GrpcGetHeadsRequest() { setResponse(new MapOfChannelAndPositionResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { CollectionOfInt32 col = MessageHelper.unpack(any, CollectionOfInt32.class); setChannels(MessageHelper.toIntArray(col)); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcGetTailsRequest ------------------------------- /** * The gRPC {@link GrpcGetTailsRequest} which wraps a protobuf request. */ public static class GrpcGetTailsRequest extends GetTailsRequest implements GrpcMessageWrapper { public GrpcGetTailsRequest() { setResponse(new MapOfChannelAndPositionResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcSeekRequest ----------------------------------- /** * The gRPC {@link SeekRequest} which wraps a protobuf request. */ public static class GrpcSeekRequest extends SeekRequest implements GrpcMessageWrapper { public GrpcSeekRequest() { setResponse(new SeekResponse()); } @Override public void setProtoMessage(Any any, Serializer serializer) { com.oracle.coherence.grpc.messages.topic.v1.SeekRequest request = MessageHelper.unpack(any, com.oracle.coherence.grpc.messages.topic.v1.SeekRequest.class); if (request.hasByPosition()) { setPositions(TopicHelper.fromProtobufChannelAndPosition(request.getByPosition())); } else { setTimestamps(TopicHelper.fromProtobufChannelAndTimestamp(request.getByTimestamp())); } } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: SeekResponse ------------------------------------- /** * The response from a {@link GrpcSeekRequest} request. */ public static class SeekResponse extends GrpcResponse { @Override @SuppressWarnings("unchecked") public Message getProtoResponse() { com.oracle.coherence.grpc.messages.topic.v1.SeekResponse.Builder builder = com.oracle.coherence.grpc.messages.topic.v1.SeekResponse.newBuilder(); Map<Integer, SeekResult> map = (Map<Integer, SeekResult>) getResult(); for (Map.Entry<Integer, SeekResult> entry : map.entrySet()) { SeekResult result = entry.getValue(); SeekedPositions.Builder positionBuilder = SeekedPositions.newBuilder(); TopicPosition head = TopicHelper.toProtobufPosition(result.getHead()); TopicPosition seeked = TopicHelper.toProtobufPosition(result.getSeekPosition()); if (head != null) { positionBuilder.setHead(head); } if (seeked != null) { positionBuilder.setSeekedTo(seeked); } builder.putPositions(entry.getKey(), positionBuilder.build()); } return builder.build(); } } // ----- inner class: GrpcHeartbeatRequest ------------------------------ /** * The gRPC {@link HeartbeatRequest} which wraps a protobuf request. */ public static class GrpcHeartbeatRequest extends HeartbeatRequest implements GrpcMessageWrapper { @Override public void setProtoMessage(Any any, Serializer serializer) { boolean fAsync = false; if (any != null) { BoolValue b = MessageHelper.unpack(any, BoolValue.class); fAsync = b != null && b.getValue(); } setAsync(fAsync); setResponse(new EmptyResponse()); } @Override public GrpcResponse getResponse() { return (GrpcResponse) super.getResponse(); } } // ----- inner class: GrpcHeartbeatRequest ------------------------------ /** * The gRPC {@link PublisherEvent} which wraps a protobuf request. */ public static class GrpcPublisherEvent extends PublisherEvent implements GrpcMessageWrapper { @Override public void setProtoMessage(Any any, Serializer serializer) { } @Override public GrpcResponse getResponse() { throw new UnsupportedOperationException(); } } // ----- data members --------------------------------------------------- private static ListMap<String, Class<?>> __mapChildren; }
apache/hbase
35,615
hbase-server/src/test/java/org/apache/hadoop/hbase/security/access/SecureTestUtil.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.hbase.security.access; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.HBaseTestingUtil; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.SingleProcessHBaseCluster; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotEnabledException; import org.apache.hadoop.hbase.Waiter.Predicate; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.MasterObserver; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.io.hfile.HFile; import org.apache.hadoop.hbase.ipc.RemoteWithExtrasException; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.security.AccessDeniedException; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.collect.Lists; import org.apache.hbase.thirdparty.com.google.common.collect.Maps; import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException; /** * Utility methods for testing security */ public class SecureTestUtil { private static final Logger LOG = LoggerFactory.getLogger(SecureTestUtil.class); private static final int WAIT_TIME = 10000; public static void configureSuperuser(Configuration conf) throws IOException { // The secure minicluster creates separate service principals based on the // current user's name, one for each slave. We need to add all of these to // the superuser list or security won't function properly. We expect the // HBase service account(s) to have superuser privilege. String currentUser = User.getCurrent().getName(); StringBuilder sb = new StringBuilder(); sb.append("admin,"); sb.append(currentUser); // Assumes we won't ever have a minicluster with more than 5 slaves for (int i = 0; i < 5; i++) { sb.append(','); sb.append(currentUser); sb.append(".hfs."); sb.append(i); } // Add a supergroup for improving test coverage. sb.append(',').append("@supergroup"); conf.set("hbase.superuser", sb.toString()); // hbase.group.service.for.test.only is used in test only. conf.set(User.TestingGroups.TEST_CONF, "true"); } public static void enableSecurity(Configuration conf) throws IOException { conf.set("hadoop.security.authorization", "false"); conf.set("hadoop.security.authentication", "simple"); conf.set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, AccessController.class.getName() + "," + MasterSyncObserver.class.getName()); conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, AccessController.class.getName()); conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY, AccessController.class.getName()); // Need HFile V3 for tags for security features conf.setInt(HFile.FORMAT_VERSION_KEY, 3); conf.set(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, "true"); configureSuperuser(conf); } public static void verifyConfiguration(Configuration conf) { String coprocs = conf.get(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY); boolean accessControllerLoaded = false; for (String coproc : coprocs.split(",")) { try { accessControllerLoaded = AccessController.class.isAssignableFrom(Class.forName(coproc)); if (accessControllerLoaded) break; } catch (ClassNotFoundException cnfe) { } } if ( !(conf.get(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY) .contains(AccessController.class.getName()) && accessControllerLoaded && conf.get(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY) .contains(AccessController.class.getName())) ) { throw new RuntimeException("AccessController is missing from a system coprocessor list"); } if (conf.getInt(HFile.FORMAT_VERSION_KEY, 2) < HFile.MIN_FORMAT_VERSION_WITH_TAGS) { throw new RuntimeException("Post 0.96 security features require HFile version >= 3"); } if (!conf.getBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, false)) { throw new RuntimeException("Post 2.0.0 security features require set " + User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY + " to true"); } } /** * An AccessTestAction performs an action that will be examined to confirm the results conform to * expected access rights. * <p> * To indicate an action was allowed, return null or a non empty list of KeyValues. * <p> * To indicate the action was not allowed, either throw an AccessDeniedException or return an * empty list of KeyValues. */ public interface AccessTestAction extends PrivilegedExceptionAction<Object> { } /** This fails only in case of ADE or empty list for any of the actions. */ public static void verifyAllowed(User user, AccessTestAction... actions) throws Exception { for (AccessTestAction action : actions) { try { Object obj = user.runAs(action); if (obj != null && obj instanceof List<?>) { List<?> results = (List<?>) obj; if (results != null && results.isEmpty()) { fail("Empty non null results from action for user '" + user.getShortName() + "'"); } } } catch (AccessDeniedException ade) { fail("Expected action to pass for user '" + user.getShortName() + "' but was denied"); } } } /** This fails only in case of ADE or empty list for any of the users. */ public static void verifyAllowed(AccessTestAction action, User... users) throws Exception { for (User user : users) { verifyAllowed(user, action); } } public static void verifyAllowed(User user, AccessTestAction action, int count) throws Exception { try { Object obj = user.runAs(action); if (obj != null && obj instanceof List<?>) { List<?> results = (List<?>) obj; if (results != null && results.isEmpty()) { fail("Empty non null results from action for user '" + user.getShortName() + "'"); } assertEquals(count, results.size()); } } catch (AccessDeniedException ade) { fail("Expected action to pass for user '" + user.getShortName() + "' but was denied"); } } /** This passes only in case of ADE for all users. */ public static void verifyDenied(AccessTestAction action, User... users) throws Exception { for (User user : users) { verifyDenied(user, action); } } /** This passes only in case of empty list for all users. */ public static void verifyIfEmptyList(AccessTestAction action, User... users) throws Exception { for (User user : users) { try { Object obj = user.runAs(action); if (obj != null && obj instanceof List<?>) { List<?> results = (List<?>) obj; if (results != null && !results.isEmpty()) { fail( "Unexpected action results: " + results + " for user '" + user.getShortName() + "'"); } } else { fail("Unexpected results for user '" + user.getShortName() + "'"); } } catch (AccessDeniedException ade) { fail("Expected action to pass for user '" + user.getShortName() + "' but was denied"); } } } /** This passes only in case of null for all users. */ public static void verifyIfNull(AccessTestAction action, User... users) throws Exception { for (User user : users) { try { Object obj = user.runAs(action); if (obj != null) { fail("Non null results from action for user '" + user.getShortName() + "' : " + obj); } } catch (AccessDeniedException ade) { fail("Expected action to pass for user '" + user.getShortName() + "' but was denied"); } } } /** This passes only in case of ADE for all actions. */ public static void verifyDenied(User user, AccessTestAction... actions) throws Exception { for (AccessTestAction action : actions) { try { user.runAs(action); fail("Expected exception was not thrown for user '" + user.getShortName() + "'"); } catch (IOException e) { boolean isAccessDeniedException = false; if (e instanceof RetriesExhaustedWithDetailsException) { // in case of batch operations, and put, the client assembles a // RetriesExhaustedWithDetailsException instead of throwing an // AccessDeniedException for (Throwable ex : ((RetriesExhaustedWithDetailsException) e).getCauses()) { if (ex instanceof AccessDeniedException) { isAccessDeniedException = true; break; } } } else { // For doBulkLoad calls AccessDeniedException // is buried in the stack trace Throwable ex = e; do { if (ex instanceof RemoteWithExtrasException) { ex = ((RemoteWithExtrasException) ex).unwrapRemoteException(); } if (ex instanceof AccessDeniedException) { isAccessDeniedException = true; break; } } while ((ex = ex.getCause()) != null); } if (!isAccessDeniedException) { fail("Expected exception was not thrown for user '" + user.getShortName() + "'"); } } catch (UndeclaredThrowableException ute) { // TODO why we get a PrivilegedActionException, which is unexpected? Throwable ex = ute.getUndeclaredThrowable(); if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (ex instanceof ServiceException) { ServiceException se = (ServiceException) ex; if (se.getCause() != null && se.getCause() instanceof AccessDeniedException) { // expected result return; } } fail("Expected exception was not thrown for user '" + user.getShortName() + "'"); } } } private static List<AccessController> getAccessControllers(SingleProcessHBaseCluster cluster) { List<AccessController> result = Lists.newArrayList(); for (RegionServerThread t : cluster.getLiveRegionServerThreads()) { for (HRegion region : t.getRegionServer().getOnlineRegionsLocalContext()) { Coprocessor cp = region.getCoprocessorHost().findCoprocessor(AccessController.class); if (cp != null) { result.add((AccessController) cp); } } } return result; } private static Map<AccessController, Long> getAuthManagerMTimes(SingleProcessHBaseCluster cluster) { Map<AccessController, Long> result = Maps.newHashMap(); for (AccessController ac : getAccessControllers(cluster)) { result.put(ac, ac.getAuthManager().getMTime()); } return result; } @SuppressWarnings("rawtypes") private static void updateACLs(final HBaseTestingUtil util, Callable c) throws Exception { // Get the current mtimes for all access controllers final Map<AccessController, Long> oldMTimes = getAuthManagerMTimes(util.getHBaseCluster()); // Run the update action c.call(); // Wait until mtimes for all access controllers have incremented util.waitFor(WAIT_TIME, 100, new Predicate<IOException>() { @Override public boolean evaluate() throws IOException { Map<AccessController, Long> mtimes = getAuthManagerMTimes(util.getHBaseCluster()); for (Map.Entry<AccessController, Long> e : mtimes.entrySet()) { if (!oldMTimes.containsKey(e.getKey())) { LOG.error("Snapshot of AccessController state does not include instance on region " + e.getKey().getRegion().getRegionInfo().getRegionNameAsString()); // Error out the predicate, we will try again return false; } long old = oldMTimes.get(e.getKey()); long now = e.getValue(); if (now <= old) { LOG.info("AccessController on region " + e.getKey().getRegion().getRegionInfo().getRegionNameAsString() + " has not updated: mtime=" + now); return false; } } return true; } }); } /** * Grant permissions globally to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantGlobal(final HBaseTestingUtil util, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin().grant( new UserPermission(user, Permission.newBuilder().withActions(actions).build()), false); } return null; } }); } /** * Grant permissions globally to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantGlobal(final User caller, final HBaseTestingUtil util, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin().grant( new UserPermission(user, Permission.newBuilder().withActions(actions).build()), false); } return null; } }); } /** * Revoke permissions globally from the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void revokeGlobal(final HBaseTestingUtil util, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin() .revoke(new UserPermission(user, Permission.newBuilder().withActions(actions).build())); } return null; } }); } /** * Revoke permissions globally from the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void revokeGlobal(final User caller, final HBaseTestingUtil util, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin() .revoke(new UserPermission(user, Permission.newBuilder().withActions(actions).build())); } return null; } }); } /** * Grant permissions on a namespace to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantOnNamespace(final HBaseTestingUtil util, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin().grant( new UserPermission(user, Permission.newBuilder(namespace).withActions(actions).build()), false); } return null; } }); } /** * Grant permissions on a namespace to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantOnNamespace(final User caller, final HBaseTestingUtil util, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin().grant( new UserPermission(user, Permission.newBuilder(namespace).withActions(actions).build()), false); } return null; } }); } /** * Grant permissions on a namespace to the given user using AccessControl Client. Will wait until * all active AccessController instances have updated their permissions caches or will throw an * exception upon timeout (10 seconds). */ public static void grantOnNamespaceUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.grant(connection, namespace, user, actions); } catch (Throwable t) { LOG.error("grant failed: ", t); } return null; } }); } /** * Revoke permissions on a namespace from the given user using AccessControl Client. Will wait * until all active AccessController instances have updated their permissions caches or will throw * an exception upon timeout (10 seconds). */ public static void revokeFromNamespaceUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.revoke(connection, namespace, user, actions); } catch (Throwable t) { LOG.error("revoke failed: ", t); } return null; } }); } /** * Revoke permissions on a namespace from the given user. Will wait until all active * AccessController instances have updated their permissions caches or will throw an exception * upon timeout (10 seconds). */ public static void revokeFromNamespace(final HBaseTestingUtil util, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin().revoke(new UserPermission(user, Permission.newBuilder(namespace).withActions(actions).build())); } return null; } }); } /** * Revoke permissions on a namespace from the given user. Will wait until all active * AccessController instances have updated their permissions caches or will throw an exception * upon timeout (10 seconds). */ public static void revokeFromNamespace(final User caller, final HBaseTestingUtil util, final String user, final String namespace, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin().revoke(new UserPermission(user, Permission.newBuilder(namespace).withActions(actions).build())); } return null; } }); } /** * Grant permissions on a table to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantOnTable(final HBaseTestingUtil util, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin().grant(new UserPermission(user, Permission.newBuilder(table) .withFamily(family).withQualifier(qualifier).withActions(actions).build()), false); } return null; } }); } /** * Grant permissions on a table to the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void grantOnTable(final User caller, final HBaseTestingUtil util, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin().grant(new UserPermission(user, Permission.newBuilder(table) .withFamily(family).withQualifier(qualifier).withActions(actions).build()), false); } return null; } }); } /** * Grant permissions on a table to the given user using AccessControlClient. Will wait until all * active AccessController instances have updated their permissions caches or will throw an * exception upon timeout (10 seconds). */ public static void grantOnTableUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.grant(connection, table, user, family, qualifier, actions); } catch (Throwable t) { LOG.error("grant failed: ", t); } return null; } }); } /** * Grant global permissions to the given user using AccessControlClient. Will wait until all * active AccessController instances have updated their permissions caches or will throw an * exception upon timeout (10 seconds). */ public static void grantGlobalUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.grant(connection, user, actions); } catch (Throwable t) { LOG.error("grant failed: ", t); } return null; } }); } /** * Revoke permissions on a table from the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void revokeFromTable(final HBaseTestingUtil util, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) { connection.getAdmin().revoke(new UserPermission(user, Permission.newBuilder(table) .withFamily(family).withQualifier(qualifier).withActions(actions).build())); } return null; } }); } /** * Revoke permissions on a table from the given user. Will wait until all active AccessController * instances have updated their permissions caches or will throw an exception upon timeout (10 * seconds). */ public static void revokeFromTable(final User caller, final HBaseTestingUtil util, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { Configuration conf = util.getConfiguration(); try (Connection connection = ConnectionFactory.createConnection(conf, caller)) { connection.getAdmin().revoke(new UserPermission(user, Permission.newBuilder(table) .withFamily(family).withQualifier(qualifier).withActions(actions).build())); } return null; } }); } /** * Revoke permissions on a table from the given user using AccessControlClient. Will wait until * all active AccessController instances have updated their permissions caches or will throw an * exception upon timeout (10 seconds). */ public static void revokeFromTableUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final TableName table, final byte[] family, final byte[] qualifier, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.revoke(connection, table, user, family, qualifier, actions); } catch (Throwable t) { LOG.error("revoke failed: ", t); } return null; } }); } /** * Revoke global permissions from the given user using AccessControlClient. Will wait until all * active AccessController instances have updated their permissions caches or will throw an * exception upon timeout (10 seconds). */ public static void revokeGlobalUsingAccessControlClient(final HBaseTestingUtil util, final Connection connection, final String user, final Permission.Action... actions) throws Exception { SecureTestUtil.updateACLs(util, new Callable<Void>() { @Override public Void call() throws Exception { try { AccessControlClient.revoke(connection, user, actions); } catch (Throwable t) { LOG.error("revoke failed: ", t); } return null; } }); } public static class MasterSyncObserver implements MasterCoprocessor, MasterObserver { volatile CountDownLatch tableCreationLatch = null; volatile CountDownLatch tableDeletionLatch = null; @Override public Optional<MasterObserver> getMasterObserver() { return Optional.of(this); } @Override public void postCompletedCreateTableAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, TableDescriptor desc, RegionInfo[] regions) throws IOException { // the AccessController test, some times calls only and directly the // postCompletedCreateTableAction() if (tableCreationLatch != null) { tableCreationLatch.countDown(); } } @Override public void postCompletedDeleteTableAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, final TableName tableName) throws IOException { // the AccessController test, some times calls only and directly the // postCompletedDeleteTableAction() if (tableDeletionLatch != null) { tableDeletionLatch.countDown(); } } } public static Table createTable(HBaseTestingUtil testUtil, TableName tableName, byte[][] families) throws Exception { TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName); for (byte[] family : families) { builder.setColumnFamily(ColumnFamilyDescriptorBuilder.of(family)); } createTable(testUtil, testUtil.getAdmin(), builder.build()); return testUtil.getConnection().getTable(tableName); } public static void createTable(HBaseTestingUtil testUtil, TableDescriptor htd) throws Exception { createTable(testUtil, testUtil.getAdmin(), htd); } public static void createTable(HBaseTestingUtil testUtil, TableDescriptor htd, byte[][] splitKeys) throws Exception { createTable(testUtil, testUtil.getAdmin(), htd, splitKeys); } public static void createTable(HBaseTestingUtil testUtil, Admin admin, TableDescriptor htd) throws Exception { createTable(testUtil, admin, htd, null); } public static void createTable(HBaseTestingUtil testUtil, Admin admin, TableDescriptor htd, byte[][] splitKeys) throws Exception { // NOTE: We need a latch because admin is not sync, // so the postOp coprocessor method may be called after the admin operation returned. MasterSyncObserver observer = testUtil.getHBaseCluster().getMaster().getMasterCoprocessorHost() .findCoprocessor(MasterSyncObserver.class); observer.tableCreationLatch = new CountDownLatch(1); if (splitKeys != null) { admin.createTable(htd, splitKeys); } else { admin.createTable(htd); } observer.tableCreationLatch.await(); observer.tableCreationLatch = null; testUtil.waitUntilAllRegionsAssigned(htd.getTableName()); } public static void createTable(HBaseTestingUtil testUtil, User user, TableDescriptor htd) throws Exception { createTable(testUtil, user, htd, null); } public static void createTable(HBaseTestingUtil testUtil, User user, TableDescriptor htd, byte[][] splitKeys) throws Exception { try (Connection con = testUtil.getConnection(user); Admin admin = con.getAdmin()) { createTable(testUtil, admin, htd, splitKeys); } } public static void deleteTable(HBaseTestingUtil testUtil, TableName tableName) throws Exception { deleteTable(testUtil, testUtil.getAdmin(), tableName); } public static void createNamespace(HBaseTestingUtil testUtil, NamespaceDescriptor nsDesc) throws Exception { testUtil.getAdmin().createNamespace(nsDesc); } public static void deleteNamespace(HBaseTestingUtil testUtil, String namespace) throws Exception { testUtil.getAdmin().deleteNamespace(namespace); } public static void deleteTable(HBaseTestingUtil testUtil, Admin admin, TableName tableName) throws Exception { // NOTE: We need a latch because admin is not sync, // so the postOp coprocessor method may be called after the admin operation returned. MasterSyncObserver observer = testUtil.getHBaseCluster().getMaster().getMasterCoprocessorHost() .findCoprocessor(MasterSyncObserver.class); observer.tableDeletionLatch = new CountDownLatch(1); try { admin.disableTable(tableName); } catch (TableNotEnabledException e) { LOG.debug("Table: " + tableName + " already disabled, so just deleting it."); } admin.deleteTable(tableName); observer.tableDeletionLatch.await(); observer.tableDeletionLatch = null; } public static String convertToNamespace(String namespace) { return PermissionStorage.NAMESPACE_PREFIX + namespace; } public static void checkGlobalPerms(HBaseTestingUtil testUtil, Permission.Action... actions) throws IOException { Permission[] perms = new Permission[actions.length]; for (int i = 0; i < actions.length; i++) { perms[i] = new Permission(actions[i]); } checkPermissions(testUtil.getConfiguration(), perms); } public static void checkTablePerms(HBaseTestingUtil testUtil, TableName table, byte[] family, byte[] column, Permission.Action... actions) throws IOException { Permission[] perms = new Permission[actions.length]; for (int i = 0; i < actions.length; i++) { perms[i] = Permission.newBuilder(table).withFamily(family).withQualifier(column) .withActions(actions[i]).build(); } checkTablePerms(testUtil, perms); } public static void checkTablePerms(HBaseTestingUtil testUtil, Permission... perms) throws IOException { checkPermissions(testUtil.getConfiguration(), perms); } private static void checkPermissions(Configuration conf, Permission... perms) throws IOException { try (Connection conn = ConnectionFactory.createConnection(conf)) { List<Boolean> hasUserPermissions = conn.getAdmin().hasUserPermissions(Lists.newArrayList(perms)); for (int i = 0; i < hasUserPermissions.size(); i++) { if (!hasUserPermissions.get(i).booleanValue()) { throw new AccessDeniedException("Insufficient permissions " + perms[i]); } } } } }